Redirecting the response from a filter throws an IllegalStateException
- by Ritesh M Nayak
I am writing a filter that will handle all authentication related tasks. My filter is a standard servlet filter as shown below
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
UserSession attribute = (UserSession)request.getSession().getAttribute("user_session_key");
if(attribute!=null && attribute.isValid())
{
//proceed as usual,
chain.doFilter(req, res);
return;
}
else
{
//means the user is not authenticated, so we must redirect him/her to the login page
((HttpServletResponse)res).sendRedirect("loginpage");
return;
}
}
But when I do this, I get an IllegalStateException thrown by Tomcat's ResponseFacade. How do I acheive this in a filter. I read in other SO threads that in TOmcat this is a problem as the response object is already commited. How do I get past this ?