springboot里编写filter过滤器常用来,拦截请求,获取其中的token,来获取用户数据,filter过滤器要被springboot加载,由于是相当于一个组件类,可能第一时间想到的就是加@Component,如下:
@Component
@WebFilter(filterName = "testFilter",urlPatterns = {"/api/*"})
public class CommonFilter implements Filter {
这里加上了@Component,虽然过滤器生效了,但是带来的结果是urlPatterns属性失效了(任何请求都会经过该过滤器)。
解决方法:去掉@Component,在程序启动类加上@ServletComponentScan :
@SpringBootApplication
@ServletComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
过滤器和urlPatterns属性均生效。