过滤器实现方式

    1. 通过FilterRegistrationBean实例注册 (优点可以设置多个自定义过滤器的顺序)
    2. 通过注解@WebFilter生效

    exp:

    1. public class Test1Filter implements Filter {
    2. @Override
    3. public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
    4. throws IOException, ServletException {
    5. // TODO Auto-generated method stub
    6. HttpServletRequest request=(HttpServletRequest)arg0;
    7. System.out.println("自定义过滤器filter1触发,拦截url:"+request.getRequestURI());
    8. arg2.doFilter(arg0,arg1);
    9. }
    10. }
    1. public class Test2Filter implements Filter {
    2. @Override
    3. public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
    4. throws IOException, ServletException {
    5. // TODO Auto-generated method stub
    6. HttpServletRequest request=(HttpServletRequest)arg0;
    7. System.out.println("自定义过滤器filter2触发,拦截url:"+request.getRequestURI());
    8. arg2.doFilter(arg0,arg1);
    9. }
    10. }
    1. import org.springframework.boot.web.servlet.FilterRegistrationBean;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import com.example.demo.filter.Test1Filter;
    5. import com.example.demo.filter.Test2Filter;
    6. @Configuration
    7. public class DemoConfiguration {
    8. @Bean
    9. public FilterRegistrationBean<Test1Filter> RegistTest1(){
    10. //通过FilterRegistrationBean实例设置优先级可以生效
    11. //通过@WebFilter无效
    12. FilterRegistrationBean<Test1Filter> bean = new FilterRegistrationBean<Test1Filter>();
    13. bean.setFilter(new Test1Filter());//注册自定义过滤器
    14. bean.setName("flilter1");//过滤器名称
    15. bean.addUrlPatterns("/*");//过滤所有路径
    16. bean.setOrder(1);//优先级,最顶级
    17. return bean;
    18. }
    19. @Bean
    20. public FilterRegistrationBean<Test2Filter> RegistTest2(){
    21. //通过FilterRegistrationBean实例设置优先级可以生效
    22. //通过@WebFilter无效
    23. FilterRegistrationBean<Test2Filter> bean = new FilterRegistrationBean<Test2Filter>();
    24. bean.setFilter(new Test2Filter());//注册自定义过滤器
    25. bean.setName("flilter2");//过滤器名称
    26. bean.addUrlPatterns("/test/*");//过滤所有路径
    27. bean.setOrder(6);//优先级,越低越优先
    28. return bean;
    29. }
    30. }
    1. 其中
    2. 1第一个bean拦截所有路径,而第二个只拦截/test/*路径
    3. 2第一个bean优先级设置了1,而第二个设置了6,越低越优先,所以过滤器1应该在过滤器2前面拦截
    4. 运行springboot,访问/test/*请求如下图,再访问/v请求如下图只拦截了过滤器1,而过滤器2路径不匹配