spring boot 配置Filter过滤器
1、通过 @WebFilter 注解来配置
@Component
@WebFilter(urlPatterns = "/webapi/*", filterName = "authFilter")
public class AuthFilter implements Filter {
......
}
再启动类中,使用注解扫描指定包 //该注解会扫描相应的包 @ServletComponentScan
2、通过 @Bean 注解来配置
我这个是写在带 @SpringBootApplication 注解的类里面的。
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean(new TestFilter());
registration.addUrlPatterns("/webapi/*"); //
registration.addInitParameter("paramName", "paramValue"); //
registration.setName("testFilter");
registration.setOrder(1);
return registration;
}
那如果有多个过虑器,怎么指定执行的顺序呢?
通过 registration.setOrder(1); 来设置
注意:
1、如果指定了 Order 属性,执行的顺序与注册的顺序是无关的;
2、数字越小,优先级越高;
详细步骤:
1)。创建过滤器,引入bean
public class SystemUrlFilter implements Filter {
@Override public void init(FilterConfig config) throws ServletException {}
@Override public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain){}
@Override public void destroy() {}
2):注册filter到配置中
@Bean
public FilterRegistrationBean systemUrlFilterBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new DelegatingFilterProxy("systemUrlFilter"));
registrationBean.addInitParameter("targetFilterLifecycle","true");
registrationBean.addUrlPatterns("/*");
registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/reg");
registrationBean.setDispatcherTypes(DispatcherType.REQUEST);
return registrationBean;
}
@Bean(name="systemUrlFilter")
public SystemUrlFilter systemUrlFilter(){
return new SystemUrlFilter();
}
-