Springboot实现过滤器
实现过滤器方式有两种:
- Filter过滤器具体实现类
- 通过@WebFilter 注解来配置
1、Filter过滤器具体实现类
1.1 实现Filter
@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());
}
}
1.2 向spring容器注册filter
@Configuration
public class FilterConfig {
@Resource
private MyTestFilter myTestFilter;
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean(myTestFilter);
registration.addUrlPatterns("/filter/*");
registration.setName("myTestFilter");
registration.setOrder(1);
return registration;
}
}
测试
2、通过@WebFilter 注解来配置
@Component
@WebFilter(urlPatterns = "/filter/*", filterName = "MyTestFilterByAnnotation")
@Slf4j
public class MyTestFilterByAnnotation 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());
}
}
标签:info,...,getClass,Springboot,Override,过滤器,public,log From: https://www.cnblogs.com/HelloWxl/p/16618327.html测试