来自jsp的response.sendRedirect():include被忽略了? [英] response.sendRedirect() from jsp:include being ignored?
问题描述
我有一个jsp文件,其中包含另一个jsp文件来检查一些值等等:
I've got a jsp file, which includes another jsp file to check some values and such:
< jsp:include page =setup.jsp/>
在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;
我看到重定向!登录到控制台,但页面继续并正常呈现。我有curl转储标题给我,并看到响应是 HTTP / 1.1 200 OK
所以它肯定没有发送302重定向。
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?
编辑:我已经确认我的回复尚未提交。 response.isCommitted()
返回 false
表示尚未发送状态代码和标题。
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.
编辑2:我曾尝试在许多其他地方调用 response.sendRedirect()
,并发现我可以在之前成功重定向。 JSP中的重定向似乎被忽略了,如果我尝试在jsp之后重定向,那么我会得到一个非法的状态异常,因为响应已经被提交了。
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.
推荐答案
< jsp:include>
在封面下使用 RequestDispatcher #include()
。单击链接以查看javadoc。以下是相关摘录(强调我的):
The <jsp:include>
uses under the covers RequestDispatcher#include()
. Click the link to see the javadoc. Here's an extract of relevance (emphasis mine):
...
...
ServletResponse对象的路径元素和参数与调用者保持不变。 包含的servlet无法更改响应状态代码或设置标头;任何改变的尝试都会被忽略。
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
...
HttpServletResponse#sendRedirect()
基本上将HTTP响应状态设置为 302
和HTTP 位置
目标网址的标头。因此完全被忽略了。
The HttpServletResponse#sendRedirect()
basically sets the HTTP response status to 302
and the HTTP Location
header to the target URL. It is thus totally being ignored.
更深层次的问题是你滥用JSP作为页面控制器/过滤器。您应该使用正常的 servlet 或过滤器这个在JSP之前运行的类。
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.
这篇关于来自jsp的response.sendRedirect():include被忽略了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!