一:注解添加
自定义一个filter 类 添加注解 @WebFilter
@WebFilter(urlPatterns = "/hello", filterName = "TestControllerFilter")
public class TestControllerFilter implements Filter {
private final Logger LOG = LogManager.getLogger(TestControllerFilter.class);
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
LOG.info("filter init......");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
LOG.info("filter start......");
chain.doFilter(request, response);
LOG.info("filter end......");
}
public void destroy() {
// TODO Auto-generated method stub
LOG.info("filter destroy......");
}
}
在spring boot启动类添加注解 @ServletComponentScan
@SpringBootApplication
@ServletComponentScan(basePackages = "filter所在的包")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
二:直接在配置类中添加 不需要注解@WebFilter
@Configuration
public class AppConfig {
@Bean
public FilterRegistrationBean TestControllerFilter(){
FilterRegistrationBean reg=new FilterRegistrationBean();
reg.setFilter(new TestControllerFilter()); //添加过滤器filter
reg.addUrlPatterns("/*"); //添加映射路径 urlpatterns
reg.setOrder(1);//设置过滤器的优先级
return reg;
}
}
这种方法比较繁琐,每个Filter类都必须进行方法配置