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, ServletRe开发者_运维问答sponse 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 ?
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.
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.
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.
精彩评论