luka032 luka032 - 10 days ago 6
Java Question

Calling Javascript alert from Java Servlet before generating JSP

I've seen many topics about on this title, but I would need something different.

How to invoke simple JavaScript alert() method, during Servlet's executing without breaking it's execution (jumping on client side)?

For example here's conception of what I would like to create if it's possible:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// CODE
// JavaScript's Alert('Hello')
// CODE
// response.sendRedirect('page.jsp')

}


So client will only see Hello and after it, page.jsp is been generated.

Answer

Pass the desired result using Dispatch process.

Servlet.java:

request.setAttribute("alertName", "Sample Result");
request.getRequestDispatcher("page.jsp").forward(request, response);

If you want to warn the user before the page.jsp starts up using the result you desired in your servlet. you can use the below code to retrieve the result and put it in the alert() method before the page load.

page.jsp:

<body>
    <input id="alertName" type="hidden" value="${alertName}"/>
</body>

above code will input the value of alertName to input element that is hidden, because we can't directly put it in the JavaScript because it process client side only. BTW ${alertName} is retrieve using EL(Expression Language), it process on server side that's why we can't directly put it in the JavaScript.

<script>
       $(window).load(function() {
           var alertName = $("#alertName").val(); // retrive using the ID of the input
           alert(alertName);  // The prompt will alert "Sample Result"
       });
</script>