我的应用程序中有2个过滤器。基于某些条件,我想选择是否执行第二个过滤器。有没有办法做到这一点?
我做了一些谷歌搜索没有成功。我希望请求继续而不执行第二个过滤器。这可能吗?
任何帮助将不胜感激。
答案 0 :(得分:57)
除了科林的回答之外,还有另外一种方法:只是不要拨打FilterChain#doFilter()
,而是RequestDispatcher#forward()
。
if (condition) {
request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response);
} else {
chain.doFilter(request, response);
}
但是这会跳过当前开启的所有过滤器,期望正在收听<dispatcher>FORWARD</dispatcher>
的过滤器。
答案 1 :(得分:9)
您可以在请求中设置属性,并在第二个过滤器中进行检查。
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);
}
//...
}
}
您可以像这样简化上面的代码:
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);
}
//...
}
}
这样您只需检查属性“executeSecondFilter”
的存在