jsp:include 中的 response.sendRedirect() 被忽略?
我有一个 jsp 文件,其中包含另一个 jsp 文件来检查一些值,例如:
在 setup.jsp 内部我已经得到一些条件代码,确定会话中是否设置了一些所需的值,如果没有,则将它们重定向到不同的页面。或者至少应该如此,但重定向似乎被忽略了。
System.err.println("Redirecting!");
response.sendRedirect("http://www.google.com");
return;
我看到“重定向!”登录到控制台,但页面继续并正常呈现。我让curl 为我转储了标头,并看到响应是HTTP/1.1 200 OK
,所以它肯定不会发送302 重定向。
知道问题是什么以及如何解决这个问题吗?
编辑:我已确认我的回复尚未提交。 response.isCommissed()
返回 false
表示状态代码和标头尚未发送。
编辑2:我尝试在许多其他地方调用 response.sendRedirect()
,发现我可以在 . JSP 内的重定向似乎被忽略,如果我尝试在 jsp 之后立即重定向,则会收到非法状态异常,因为响应已提交。
I've got a jsp file, which includes another jsp file to check some values and such:
<jsp:include page="setup.jsp" />
Inside the setup.jsp I've got some conditional code which determines if some needed values are set in the session and if not redirects them to a different page. Or at least it is supposed to, but the redirect seems to be getting ignored.
System.err.println("Redirecting!");
response.sendRedirect("http://www.google.com");
return;
I see "Redirecting!" get logged to the console, but the page continues on and renders normally. I had curl dump the headers for me and saw that the response is HTTP/1.1 200 OK
so it definitely isn't sending a 302 redirect.
Any idea what the problem is and how I can fix this?
EDIT: I have verified that my response is not yet committed. response.isCommitted()
returns false
meaning the status code and headers have not been sent yet.
EDIT 2: I've tried calling response.sendRedirect()
in many other places and find that I can successfully redirect before the . The redirect inside the JSP seems to be ignored and if I try to redirect right AFTER the jsp then I get an illegal state exception because the response has already been committed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在幕后使用RequestDispatcher#include()
。单击该链接可查看 javadoc。这是相关性的摘录(强调我的):HttpServletResponse#sendRedirect()
基本上将 HTTP 响应状态设置为302
并且 HTTP目标 URL 的Location
标头。因此它完全被忽视了。更深层次的问题是您滥用 JSP 作为页面控制器/过滤器。您实际上应该使用普通的 servlet 或 filter 类,它的运行远远早于 JSP。
The
<jsp:include>
uses under the coversRequestDispatcher#include()
. Click the link to see the javadoc. Here's an extract of relevance (emphasis mine):The
HttpServletResponse#sendRedirect()
basically sets the HTTP response status to302
and the HTTPLocation
header to the target URL. It is thus totally being ignored.The deeper problem is that you're abusing JSP as a page controller/filter. You should actually be using a normal servlet or filter class for this which runs far before JSP.
重定向标头(我相信)需要位于页面顶部。查看 HTML 规范以供参考。
您是否尝试过将其放在页面的最顶部?代码示例将帮助我们调试......
The redirect header (I believe) needs to be at the top of the page. View the HTML spec for reference.
Have you tried placing it at the very top of the page? A code sample would help us debug...