假如应用中存在多个过滤器,如何在第一个过滤器处理时根据某些条件跳过后续过滤器处理?这里提供了两种方式来解决这个问题。
方式一:在后续过滤器中根据前面过滤器处理后设置的标识手动跳过。标识可以放在 Request Attributes 里。
public class FirstFilter implements Filter { //...1public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 2 servletRequest.setAttribute("executeSecondFilter", true); 3 //... 4 if(someReason) 5 servletRequest.setAttribute("executeSecondFilter", false); 6 filterChain.doFilter(servletRequest, servletResponse); 7}
}
public class SecondFilter implements Filter {
//..1public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 2 if (servletRequest.getAttribute("executeSecondFilter") == null || !((Boolean) servletRequest.getAttribute("executeSecondFilter"))) { 3 filterChain.doFilter(servletRequest, servletResponse); 4 } 5 //... 6}
}
方式二:过滤器处理时,不进行后续过滤器链处理(FilterChain#doFilter()
),而是直接转发请求给 Servlet(RequestDispatcher#forward()
)。
if (condition) { request.getRequestDispatcher(httpServletRequest.getServletPath() + httpServletRequest.getPathInfo()).forward(request, response); } else { chain.doFilter(request, response); }
这样会跳过后续的所有过滤器处理,如果有某个过滤器仍然需要进行处理,那可以在 web.xml 中配置该过滤器 <filter-mapping>:
<dispatcher>FORWARD</dispatcher>
细节可参阅 Servlet 3.0 规范(JSR-315)6.2.5 Filters and the RequestDispatcher
参考: