SpringBoot项目@WebFilter过滤器urlPatterns配置失效的解决方案,以及多个filter过滤器demo

版本说明: spring-boot-starter-parent   2.1.11.RELEASE

1:定义两个filter过滤器类

public class MyFilter1 implements Filter {
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException { 
       // todo XXX
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}

再定义第二个过滤器 MyFilter2,代码同上。 注意:不添加任何注解!

2:filter注册为一个bean

在SpringBoot启动类里添加@Configuration 注解,这可以让SpringBoot认得@Bean注解。然后启动类里添加如下代码:

@Bean
    MyFilter1 getApiAuthenticationFilter1(){
        return new MyFilter1();
    }

    @Bean("myFilter1RegistrationBeanName")
    public FilterRegistrationBean<MyFilter1> registerFilter1(MyFilter1 myFilter1) {
        FilterRegistrationBean<MyFilter1> registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(myFilter1);
        registrationBean.addUrlPatterns("/account/*"); //url拦截
        registrationBean.setOrder(1);
        registrationBean.setAsyncSupported(true);
        return registrationBean;
    }

    @Bean //这里特意注册为一个bean,是可以让spring容器在filter类里注入@Autowited字段
    MyFilter2 getInnerApiAuthFilter1(){
        return new MyFilter2();
    }

    @Bean("myFilter2RegistrationBeanName") //注意,如果是多个filter,一定要给bean命名不通的名字
    public FilterRegistrationBean<MyFilter2> registerFilter2(MyFilter2 myFilter2) { //传参方式而非new对象的方式,可以从spring容器里得到bean对象
        FilterRegistrationBean<MyFilter2> registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(myFilter2);
        registrationBean.addUrlPatterns("/api/*");
        registrationBean.setOrder(2);
        registrationBean.setAsyncSupported(true);
        return registrationBean;
    }

3:修改log日志打印级别为debug

在application.properties配置文件中,添加日志级别配置:logging.level.org.springframework.boot=debug

 

4:日志打印验证url拦截

 

2020-01-02 19:35:19.125 DEBUG 61918 [main] o.s.b.w.s.ServletContextInitializerBeans : Mapping filters: springSecurityFilterChain urls=[/*], 
          filterRegistrationBean urls=[/account/*], filterRegistrationBean urls=[/api/*], characterEncodingFilter urls=[/*] 2020-01-02 19:35:19.125 DEBUG 61918 [main] o.s.b.w.s.ServletContextInitializerBeans : Mapping servlets: dispatcherServlet urls=[/],
          messageDispatcherServlet urls=[/services/*]

 

从以上日志打印可以看出url拦截已经生效了。

以上代码亲测验证有效。

至于controller的代码拦截试验,此处不方便贴出,请大家各自验证。

 

 

上一篇:springmvc开发之配置Servlet三大组件(Servlet、Filter、Listener)


下一篇:HystrixDashboard图表化hystrix/turbine.stream问题探索