How to skip a filter in the filter chain in java
I have 2 filters in my application. Based on some condition, I want to choose whether to execute the second filter or not. Is there a way to do this?
I d开发者_如何学Pythonid some googling with no success. I want the request to continue without executing the second filter. Is that possible?
Any help will be appreciated.
In addition to Colin's answer, there's another way: just don't call FilterChain#doFilter()
, but RequestDispatcher#forward()
.
if (condition) {
request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response);
} else {
chain.doFilter(request, response);
}
But this will skip all filters from current on, expect of the ones which are listening on <dispatcher>FORWARD</dispatcher>
.
You can set an Attribute in your request and check it in your second filter.
public class FirstFilter implements Filter {
//...
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setAttribute("executeSecondFilter", true);
//...
if(someReason)
servletRequest.setAttribute("executeSecondFilter", false);
filterChain.doFilter(servletRequest, servletResponse);
}
}
public class SecondFilter implements Filter {
//..
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletRequest.getAttribute("executeSecondFilter") == null || !((Boolean) servletRequest.getAttribute("executeSecondFilter"))) {
filterChain.doFilter(servletRequest, servletResponse);
}
//...
}
}
You can simplify the code above like this :
public class FirstFilter implements Filter {
//...
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//...
if(someReason)
servletRequest.setAttribute("executeSecondFilter", false);
filterChain.doFilter(servletRequest, servletResponse);
}
}
public class SecondFilter implements Filter {
//..
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletRequest.getAttribute("executeSecondFilter") != null) {
filterChain.doFilter(servletRequest, servletResponse);
}
//...
}
}
This way you just check the presence of the attribute "executeSecondFilter"
精彩评论