SpringBoot 过滤器配置有三种方式
1. @ServletComponentScan + @WebFilter, 可配置过滤路径, 但没有顺序(顺序是由过滤器命名决定)
在启动类上使用 @ServletComponentScan, 在过滤器类上使用 @WebFilter(urlPatterns = {"/test/path"})
@SpringBootApplication
@ServletComponentScan
public class ServicemapServicecenterBackendApplication {
public static void main(String[] args) {
SpringApplication.run(ServicemapServicecenterBackendApplication.class, args);
}
}
@WebFilter(urlPatterns = {"/test"})
public class FilterTwo extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("************************** FilterTwo **************************");
filterChain.doFilter(request, response);
}
}
2. @Component + @Order(100), 不可配置过滤路径, 可以通过@Order配置顺序
在过滤器类上使用 @Component , @Order(100) 数值越小优先级越高
@Component
@Order(100)
public class FilterOne extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("************************** FilterOne **************************");
filterChain.doFilter(request, response);
}
}
3. @SpringBootConfiguration + @Order, 可配置过滤路径, 可以通过@Order配置顺序, 也可以在代码中setOrder(100)配置 (推荐方式)
@Order(100)
public class FilterOne extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("************************** FilterOne **************************");
filterChain.doFilter(request, response);
}
}
@SpringBootConfiguration
public class FilterConfig {
@Bean
public FilterRegistrationBean<FilterOne> filterOneRegister() {
FilterRegistrationBean<FilterOne> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(new FilterOne());
filterRegistrationBean.addUrlPatterns("/*");
// filterRegistrationBean.setOrder(100);
return filterRegistrationBean;
}
}