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

java, jsp, jspinclude, redirect

Solution

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.

Problem

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.

Original source