如何在Java中的过滤器链中跳过过滤器

我的应用程序中有2个过滤器。根据某些条件,我想选择是否执行第二个过滤器。有没有办法做到这一点?

我做了一些谷歌搜索,但没有成功。我希望请求继续执行而不执行第二个过滤器。那可能吗?

任何帮助将不胜感激。

回答:

您可以在请求中设置一个属性,然后在第二个过滤器中对其进行检查。

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”的存在

以上是 如何在Java中的过滤器链中跳过过滤器 的全部内容, 来源链接: utcz.com/qa/414383.html

回到顶部