luka032 luka032 - 1 year ago 94
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 {

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


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

Answer Source

Pass the desired result using Dispatch process.

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.


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

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.

       $(window).load(function() {
           var alertName = $("#alertName").val(); // retrive using the ID of the input
           alert(alertName);  // The prompt will alert "Sample Result"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download