最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Showing JavaScript alert before JSP forward - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 3

The 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.

发布评论

评论列表(0)

  1. 暂无评论