需求描述

在登录授权时,需要从 header 中获取 token 进行鉴权,通常使用过滤器处理指定的访问请求,但在使用 @WebFilter 注解时,发现其路径匹配模式不生效,即 url、urlPatterns 属性配置后,拦截了所有请求。

解决方案

@WebServlet,@WebFilter,@WebListener 注解,需要和 @ServletComponentScan 注解配套使用,表明其为 servlet 组件,而不是普通的 spring 组件,当使用 @Component 注解后,会优先被注册为 spring 组件,导致 servlet 扫描器失效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@ServletComponentScan("包名")
@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
// 扫描所有 user 下的路径
@WebFilter("user/*")
public class TestFilter implements Filter{
}

补充

可以通过 FilterRegistrationBean 装饰器,以编程方式手动注册过滤器。

评论