Springboot实现过滤器有以下俩种方式,第一种方式俩步走,即向spring容器注册filter
第一种:
1.Filter过滤器具体实现类
代码语言:javascript复制@Component
@Slf4j
public class MyTestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("[ {} ] 创建啦...", this.getClass().getSimpleName());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("[ {} ] 执行啦...", this.getClass().getSimpleName());
chain.doFilter(request, response);
}
@Override
public void destroy() {
log.info("[ {} ] 被摧毁啦...", this.getClass().getSimpleName());
}
}
2.向spring容器注册filter
代码语言:javascript复制@Configuration
public class FilterConfig {
@Resource
private MyTestFilter myTestFilter;
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean(myTestFilter);
registration.addUrlPatterns("/filter/*");
registration.setName("testFilter");
registration.setOrder(1);
return registration;
}
}
第二种:
通过@WebFilter 注解来配置
代码语言:javascript复制@Component
@WebFilter(urlPatterns = "/filter/*", filterName = "myTestFilter")
@Slf4
public class MyTestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("[ {} ] 创建啦...", this.getClass().getSimpleName());
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("[ {} ] 执行啦...", this.getClass().getSimpleName());
chain.doFilter(request, response);
}
@Override
public void destroy() {
log.info("[ {} ] 被摧毁啦...", this.getClass().getSimpleName());
}
}
还需要在 SpringBootApplication 上使用@ServletComponentScan
注解后 Servlet可以直接通过@WebServlet注解自动注册 Filter可以直接通过@WebFilter注解自动注册 Listener可以直接通过@WebListener 注解自动注册