Springboot实现过滤器的两种方式
作者:一个风轻云淡
今天通过本文给大家分享Springboot实现过滤器的两种方式,第一种是spring容器注册filter,第二种方式是通过@WebFilter 注解来配置,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
Springboot实现过滤器有以下俩种方式,第一种方式俩步走,即向spring容器注册filter
第一种:
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()); } }
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("testFilter"); registration.setOrder(1); return registration; } }
第二种:
通过@WebFilter 注解来配置
@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 注解自动注册
到此这篇关于Springboot实现过滤器的文章就介绍到这了,更多相关Springboot过滤器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!