在 JSP 转发之前显示 JavaScript 警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13308082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Showing JavaScript alert before JSP forward
提问by gautam vegeta
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.
我试图在执行转发之前在 jsp 页面的正文中用 javascript 警告一条消息并且它没有被执行。
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.
这里我想在将控件传递给另一个jsp页面之前提醒消息。我该怎么做。在这里,如果我删除转发部分,警报消息将显示在警报框中。
回答by Denys Séguret
The forward
replaces the content of the page, which is not sent to the browser.
该forward
替换页,这是不发送到浏览器的内容。
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");
%>
回答by BalusC
Why are you writing JS code via Java scriptletsin JSP while JSP itself already offers an excellent template to write HTML/JS code plain in?
为什么你在 JSP 中通过 Java scriptlets编写 JS 代码,而 JSP 本身已经提供了一个很好的模板来编写纯 HTML/JS 代码?
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 uncommitted, it discards everything which is written to the response buffer beforehand.
无论如何,只需使用JS而不是JSP来执行重定向。您知道,Java/JSP 在网络服务器上运行并生成 HTML/JS,而后者仅在网络浏览器中运行。转发基本上替换了请求/响应目的地,如果响应未提交,它会丢弃事先写入响应缓冲区的所有内容。
Here's how you could do it with in normal HTML/JS:
以下是您可以在普通 HTML/JS 中使用的方法:
<script>
alert('Hello');
window.location = 'secondpage.jsp';
</script>
That's it. See, you don't need to put it in some scriptletugliness at all. Just put it in its entirety in the JSP file.
而已。看,你根本不需要把它放在一些丑陋的脚本中。只需将其完整地放在 JSP 文件中即可。