response.sendRedirect() from jsp:include being ignored?

一笑奈何 提交于 2019-12-18 05:01:06

问题


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.


回答1:


The <jsp:include> uses under the covers RequestDispatcher#include(). Click the link to see the javadoc. Here's an extract of relevance (emphasis mine):

...

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.

...

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.

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.




回答2:


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



来源:https://stackoverflow.com/questions/6637990/response-sendredirect-from-jspinclude-being-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!