charu joshi
charu joshi

Reputation: 113

Call Javascript function in Servlet, after servlet responce

I have a jsp page. There is a form in the jsp page and when I press submit the control goes to the servlet and the servlet sends the response in the same jsp. I want to call a javascript fuction after the response is called.

String operation = request.getParameter("operation");
        if (operation.equals("create")) {
            String value = null;
            Map<String, String> requestMap = new HashMap<>();
            String entity = request.getParameter("entity");
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String paramName = parameterNames.nextElement();
                if (paramName.equals("operation") || paramName.equals("entity")) {
                    value = request.getParameter(paramName);
                } else {
                    value = Constraints.toTitleCase(request.getParameter(paramName));
                }
                requestMap.forEach((k,v)->System.out.println("{KeY} :"+k+".....{VAlue} :"+v));
                requestMap.put(paramName, value);
            }
            masterHelper.processRequest(requestMap);
            log.debug("js");
            response.getOutputStream().println("<script>sucess();('hello');</script>");
            response.sendRedirect("user/master/" + entity + ".jsp");
        }

Upvotes: 1

Views: 555

Answers (2)

Shalin Patel
Shalin Patel

Reputation: 1099

All you can do is use just set extra variable for it and then based on the value of that variable call the javascript function. You can follow steps below

  1. In your servlet set a boolean variable

    boolean isResponse=true;

  2. Then add it to your response

    request.setAttribute("isResponse", isResponse);

  3. the add below code in your jsp.

    ${ isResponse=="true"?'windows.onLoad=functionname()':'' }

And you are done with it.

Upvotes: 1

Kedar Brahme
Kedar Brahme

Reputation: 31

Looks like you are redirecting the page .

response.sendRedirect("user/master/" + entity + ".jsp");

try sending the function definition also.

Upvotes: 2

Related Questions