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

如何在Java中的过滤器链中跳过过滤器,第1张

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

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

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5489733.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存