在Spring Boot上调用GenericFilterBean的doFilter()之后返回

时间:2019-02-04 18:54:30

标签: spring-boot spring-mvc spring-security filter servlet-filters

我在Spring引导项目中使用GenericFilterBean作为过滤器。

在某些情况下,我想在我的过滤器逻辑上传递下一个过滤器。

我的过滤器如下所示;

public class MyFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            if (anyCondition){
                chain.doFilter();
                return;         
            }

            if (anyCondition){
                chain.doFilter();
                return;         
            }

            if (anyCondition){
                chain.doFilter();
                return;         
            }

            chain.doFilter();

        }

    }

如果不返回,它将调用其他chain.doFilter(),这就是我返回的方式。

在调用chain.doFilter()之后,返回是否会导致任何问题?

处理这种情况是否正确?

1 个答案:

答案 0 :(得分:1)

您的代码将始终调用chain.doFilter(而不是doChain)

例如

    public class MyFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            //this gets executed before other filters
            some code here

            //now we execute other filters
            chain.doFilter(request, response); 

            //this code gets executed after the 'next' filters are done
            some code here

        }

    }

但是您的代码总是执行 next 过滤器,然后完成。 您的代码很好,但是您可以使用if then else语句代替

    public class MyFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            if (condition1){
                //do something for condition1
            } else if (condition2) {
                //do something for condition2
            }  else if (condition3) {
                //do something for condition3
            }
            chain.doChain();

        }

    }