自定义DelegatingFilterProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @author cuishiying
* @date 2021-01-22
*/
@Configuration
public class WebConfig {

@Bean
public Filter tokenAuthFilter() {
return new TokenAuthFilter();
}
/** * 注册filter,统一处理api开头的请求 * @return FilterRegistrationBean */
@Bean
public FilterRegistrationBean tokenAuthFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
// DelegatingFilterProxy把servlet 容器中的filter同spring容器中的bean关联起来, spring会去查找tokenAuthFilter的filter
registration.setFilter(new DelegatingFilterProxy("tokenAuthFilter"));
registration.addUrlPatterns("/*");
registration.setName("tokenAuthFilter");
registration.setOrder(1);
return registration;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @author cuishiying
* @date 2021-01-22
*/
public class TokenAuthFilter implements Filter {

public TokenAuthFilter() {
System.out.println("myFilter");
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("filter...");
filterChain.doFilter(servletRequest, servletResponse);
}
}

springboot程序启动即可自动调用TokenAuthFilter