I am trying to alert a message in javascript inside the body of a jsp page before a forward is performed and its not getting executed.
Here's the code
<%
...
out.write("<script type='text/javascript'>\n");
out.write("alert( " + "' Hello '" + ");\n");
out.write("</script>\n");
request.getRequestDispatcher("secondpage.jsp").forward(request, response);
%>
Here I want to alert the message before I pass the control to another jsp page.How can I do this. Here if i remove the forwarding part the alert message gets displayed in an alert box.
I am trying to alert a message in javascript inside the body of a jsp page before a forward is performed and its not getting executed.
Here's the code
<%
...
out.write("<script type='text/javascript'>\n");
out.write("alert( " + "' Hello '" + ");\n");
out.write("</script>\n");
request.getRequestDispatcher("secondpage.jsp").forward(request, response);
%>
Here I want to alert the message before I pass the control to another jsp page.How can I do this. Here if i remove the forwarding part the alert message gets displayed in an alert box.
Share Improve this question edited Nov 9, 2012 at 12:57 BalusC 1.1m376 gold badges3.7k silver badges3.6k bronze badges asked Nov 9, 2012 at 12:28 gautam vegetagautam vegeta 6537 gold badges14 silver badges28 bronze badges2 Answers
Reset to default 3The forward
replaces the content of the page, which is not sent to the browser.
As the browser doesn't even receive the script you write, it can't execute it.
Supposing you'd want the user to see the alert one second before being redirected, you could do this :
<%
out.write("<script type='text/javascript'>\n");
out.write("alert(' Hello ');\n");
out.write("setTimeout(function(){window.location.href='secondpage.jsp'},1000);");
out.write("</script>\n");
%>
Why are you writing JS code via Java scriptlets in JSP while JSP itself already offers an excellent template to write HTML/JS code plain in?
Anyway, just use JS to perform a redirect instead of JSP. You know, Java/JSP runs on webserver and produces HTML/JS which in turn runs in webbrowser only. A forward basically replaces the request/response destination and if the response is unmitted, it discards everything which is written to the response buffer beforehand.
Here's how you could do it with in normal HTML/JS:
<script>
alert('Hello');
window.location = 'secondpage.jsp';
</script>
That's it. See, you don't need to put it in some scriptlet ugliness at all. Just put it in its entirety in the JSP file.