Monday, August 27, 2007

sendRedirect & servlets 2.3 specs

Recently I had a sleepless night in redirecting the non-authenticated users on my website to a login page.

I was trying to do this through an include file within a JSP.
But every time I do this I got an error - "Cannot set header. Response already committed".

I searched a lot and found that as per the servlets specification2.3 you cannot do a "response.sendRedirect" from an include JSP.
Either the redirection code should be the first line in JSP or it should be done in servlets.

The workaround for this problem is to manipulate the Http Headers and force them to redirect to the desired URL.

Here is the 2 Lines of Code which can be replaced by "response.sendRedirect": -

response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY ); //302 redirect
response.setHeader("location","jsp/login.jsp"); //Name of the JSP page.

No comments: