title: Redirecting the response from a filter throws an IllegalStateException
body: <p>I am writing a filter that will handle all authentication related tasks. My filter is a standard servlet filter as shown below</p>
  
  <pre><code>@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 &amp;&amp; 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;
      }      
    }
  </code></pre>
  
  <p>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 ? </p>