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

2022-09-01 14:59:21

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

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

任何帮助将不胜感激。


答案 1

除了Colin的答案之外,还有另一种方法:不要调用FilterChain#doFilter(),而是RequestDispatcher#forward()。而要调用Listenchain#doFilter()。

if (condition) {
    request.getRequestDispatcher(((HttpServletRequest) request).getServletPath()).forward(request, response);
} else {
    chain.doFilter(request, response);
}

但是,这将跳过当前打开的所有过滤器,期望正在侦听的过滤器。<dispatcher>FORWARD</dispatcher>


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


推荐