1. 使用@WebFilter注解(适用于Servlet API项目)
import jakarta.servlet.annotation.WebFilter;
@WebFilter(urlPatterns = "/*") // 拦截所有请求
public class TokenFilter implements Filter {
// 实现doFilter方法,添加过滤逻辑
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// ... 过滤器逻辑
chain.doFilter(request, response);
}
// 其他生命周期方法如init和destroy...
}
2. 使用Spring的FilterRegistrationBean(推荐)
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<TokenFilter> tokenFilterRegistration() {
FilterRegistrationBean<TokenFilter> registration = new FilterRegistrationBean<>();
registration.setFilter(new TokenFilter());
// 设置拦截规则
registration.addUrlPatterns("/*"); // 拦截所有请求
// 可以设置过滤器名称、初始化参数等
registration.setName("tokenFilter");
// 设置过滤器执行顺序,默认为0,数值越小优先级越高
registration.setOrder(1);
return registration;
}
}
// TokenFilter类实现javax.servlet.Filter接口
public class TokenFilter implements Filter {
// ...
}
3. 如果过滤器是Spring Bean,可以通过继承GenericFilterBean
import org.springframework.web.filter.GenericFilterBean;
public class TokenFilter extends GenericFilterBean {
// 实现doFilterInternal方法替代doFilter方法
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// ... 过滤器逻辑
chain.doFilter(request, response);
}
}
// 注册到Spring容器中
@Configuration
public class FilterConfig {
@Bean
public TokenFilter tokenFilter() {
return new TokenFilter();
}
// 若需指定URL模式或排序,同样可以使用FilterRegistrationBean
@Bean
public FilterRegistrationBean<TokenFilter> tokenFilterRegistration(TokenFilter tokenFilter) {
FilterRegistrationBean<TokenFilter> registration = new FilterRegistrationBean<>(tokenFilter);
registration.addUrlPatterns("/*");
registration.setOrder(1);
return registration;
}
}