springboot过滤器FilterRegistrationBean
有2种⽅式可以实现过滤器
1:通过FilterRegistrationBean实例注册
2:通过@WebFilter注解⽣效
这⾥选择第⼀种,因为第⼆种不能设置过滤器之间的优先级
为了演⽰优先级,这⾥创建2个测试过滤器类:Test1Filter、Test2Filter
通过实现javax.servlet.Filter接⼝,覆盖其doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)⽅法,决定拦截或放⾏public class Test1Filter implements Filter {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)arg0;
System.out.println("⾃定义过滤器filter1触发,拦截url:"+RequestURI());
arg2.doFilter(arg0,arg1);
}
}
public class Test2Filter implements Filter {
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)arg0;
System.out.println("⾃定义过滤器filter2触发,拦截url:"+RequestURI());
arg2.doFilter(arg0,arg1);
}
}
通过在springboot的configuration中配置不同的FilterRegistrationBean实例,来注册⾃定义过滤器
这⾥创建⼀个configuration类
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import t.annotation.Bean;
import t.annotation.Configuration;
ample.demo.filter.Test1Filter;
ample.demo.filter.Test2Filter;
@Configuration
public class DemoConfiguration {
@Bean
public FilterRegistrationBean<Test1Filter> RegistTest1(){
//通过FilterRegistrationBean实例设置优先级可以⽣效
//通过@WebFilter⽆效
FilterRegistrationBean<Test1Filter> bean = new FilterRegistrationBean<Test1Filter>();
bean.setFilter(new Test1Filter());//注册⾃定义过滤器
bean.setName("flilter1");//过滤器名称
bean.addUrlPatterns("/*");//过滤所有路径
bean.setOrder(1);//优先级,最顶级
return bean;
}
@Bean
public FilterRegistrationBean<Test2Filter> RegistTest2(){
//通过FilterRegistrationBean实例设置优先级可以⽣效
//通过@WebFilter⽆效
FilterRegistrationBean<Test2Filter> bean = new FilterRegistrationBean<Test2Filter>();
bean.setFilter(new Test2Filter());//注册⾃定义过滤器
bean.setName("flilter2");//过滤器名称
bean.addUrlPatterns("/test/*");//过滤所有路径
bean.setOrder(6);//优先级,越低越优先
return bean;
}
}
其中
1第⼀个bean拦截所有路径,⽽第⼆个只拦截/test/*路径
2第⼀个bean优先级设置了1,⽽第⼆个设置了6,越低越优先,所以过滤器1应该在过滤器2前⾯拦截
spring framework运⾏springboot,访问/test/*请求如下图,再访问/v请求如下图只拦截了过滤器1,⽽过滤器2路径不匹配
如果把.addUrlPatterns();中拦截路径改成⼀样/test/*,则所有请求,都会触发2个过滤器,⽽且过滤器1永远在最先拦截

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。