How to embed Javascript code with include file

Discussions

Web tier: servlets, JSP, Web frameworks: How to embed Javascript code with include file

  1. How to embed Javascript code with include file (4 messages)

    After my servlet completes processing of data received, how do I show a javascript alert message like 'processing done' and then include (request dispatcher, or forward to) a jsp file together?
    That is, how do I display the included/forwarded jsp file with the javascript alert message embedded in its body tag as if they are in the same file.
  2. in body of the servlet:
    ======================
    //processing data here

    ServletContext stx = getServletConfig().getServletContext() ;
    stx.getRequestDispatcher("/result.jsp").include(req, res);
    =======================


    and in the result.jsp, put your alert message in the head section. example like:
    ===========================
    <%@ page language="java" %>
    response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
    response.setHeader("Pragma","no-cache"); //HTTP 1.0
    response.setDateHeader ("Expires", 0);
    %>
    <html>
    <head>
    <SCRIPT>
      <!--
      alert("done the job");
      //-->
    </Script>
    </head>
    <body>
     //do other thing after raise the alert
    </body>
    </html>
    ========================

  3. Thanks, your suggestion is fine.

    But if I do this my result.jsp will always display "done the job" whether it is directly executed from the browser or included by a servlet. This is what I do not want.

    Is there any other way that some javascript is added only by the servlet before it include /forward to a jsp. So that the "done the job" message is displayed only when the servlet is called and executed by a link.
  4. When call forward to/include the result page, add an extra parameter and in the result page, check if you can get this parameter's value or not. If you can get it , so the caller page must be the servlet!!
  5. Since you are 'forwarding' the request and response object, you can store an attribute into the request object that is checked when the JSP is loaded. The syntax for this code is quite simple. Assuming the name of your HttpServletRequest object's name is 'request' in your overriding method (i.e. doPost/doGet (HttpServletRequest request, HttpServletResponse response) ), you can simply code:

    request.setAttribute("flag", new Boolean(true));

    And then in your JSP, you would call:

    <%
    if((Boolean)request.getAttribute("flag").booleanValue()) {
    %>
        // print javascript
    <%
    } else {
        // redirect? do server-side stuff...
    %>
       <!-- html here -->
    <%
    }
    %>

    Sorry this code sucks =P. Anyway, storing objects in the request object is a good method of passing information. That's why I converted the boolean primitive to Boolean and then converted it back once it got in the JSP. Hope this helps!