思路
在 springboot 里注册过滤器有两种思路,一种是在 configuration 里提供 FilterRegistrationBean 的 bean.
第二种是使用 @WebFilter 注解,并且注意使用 @ServletComponentScan 扫描包,两种方式注册过滤器。
第一种方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class LogCostFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); filterChain.doFilter(servletRequest,servletResponse); System.out.println("Execute cost="+(System.currentTimeMillis()-start)); } @Override public void destroy() { } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Configuration public class FilterConfig { @Bean public FilterRegistrationBean registFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new LogCostFilter()); registration.addUrlPatterns("/*"); registration.setName("LogCostFilter"); registration.setOrder(1); return registration; } }
|
第二种方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @WebFilter(urlPatterns = "/*", filterName = "logFilter2") public class LogCostFilter2 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { long start = System.currentTimeMillis(); filterChain.doFilter(servletRequest, servletResponse); System.out.println("LogFilter2 Execute cost=" + (System.currentTimeMillis() - start)); } @Override public void destroy() { } }
|
这里直接用@WebFilter就可以进行配置,同样,可以设置url匹配模式,过滤器名称等。这里需要注意一点的是@WebFilter这个注解是Servlet3.0的规范,并不是Spring boot提供的。除了这个注解以外,我们还需在配置类中加另外一个注解:@ServletComponetScan,指定扫描的包。
1 2 3 4 5 6 7 8
| @SpringBootApplication @MapperScan("com.pandy.blog.dao") @ServletComponentScan("com.pandy.blog.filters") public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
|
参考链接
https://www.cnblogs.com/paddix/p/8365558.html