How do I implement a dummy filter to exclude a file from being filtered?
I am trying to implement a filter for all my files excluding login.jsp. I understand that filter mapping cannot exclude certain files. What I need to do is to create another filter to map just the login.jsp. How do I create another file that with url pattern /login.jsp and without SessionFilter being processed after it? Here is part of my code for session filter for all files.
public class SessionFilter implements Filter{
RequestDispatcher rd = null;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException{
HttpServletRequest request = (HttpServletRequest)request;
HttpSession session = request.getSession();
// New Session so forward to login.jsp
if (session.isNew()){
rd = request.get开发者_C百科RequestDispatcher("login.jsp");
rd.forward(request, response);
}
// Not a new session so continue to the requested resource
else{
filterChain.doFilter(request, response);
}
}
You can check if the requested path is in your "excluded list" with request.getServletPath()
.
If you want a new Filter
separated from SessionFilter
, you could either set a special flag as request attribute (such as "loginPage") which will be checked by other filters (if you want a new Filter
separated from SessionFilter
) or you can simply not invoke the chain.doFilter()
.
If you're modifying SessionFilter
, just don't redispatch to "login.jsp"
You don't need a new filter. You could check it at your own filter.
if(request.getServletPath().equals("login.jsp") || !session.isNew()) { // or "/login.jsp", not sure about this
filterChain.doFilter(request, response);
} else { // session is new and it's not login.jsp
rd = request.getRequestDispatcher("login.jsp");
rd.forward(request, response);
}
But I don't like this kind of approach. It seems like rewriting the JAAS API for servlets. And it implies hardcoding jsp paths, which could be not a good idea in order of maintenance and portability.
精彩评论