views:

229

answers:

3

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 ?

A: 

Are you committing the response somewhere else in the filter chain? Usually this is not done until you start writing to the response's OutputStream in the servlet itself. In your filter method you are however either forwarding the request to the next element in the filter chain or eventually the servlet itself, or you are sending a redirect, which at this point should be ok unless a previous filter already has (perhaps indirectly) committed the response.

jarnbjo
I dont think any other filters are writing to the response and as I checked, this is the first filter. It seems pretty trivial but I am unable to get past this :(
Ritesh M Nayak
+1  A: 

Perhaps you have other filters defined that are executed before this one in the filter chain. That/these filters may be using the response so that it is not in a legal state for redirect at the time the execution reaches your filter.

Move your filter declaration at the top of filter declarations.

Bozho
Or maybe the other filter is doing both a redirect/forward and continue of chain. Regardless indeed move the filter to top and it should work as expected.
BalusC
A: 

Your filter looks fine, another filter must be running before your filter and committing the response.

Make sure that your filter-mapping elements are in the order you'd like them applied, the order of the filter definition elements doesn't matter.

To make sure that this is not the problem, try removing all other filter-mappings.

Geoff