springboot 配置 自定的 过滤器需要将自定义的过滤配实现 javax.servlet.Filter接口
demo1:在自定义过滤器上添加组件注解
package com.dayu.filter; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; import java.util.Date; /** * @author 大宇 * Description 过滤器处理所有请求 * 这里写两种配置方式:一种在myFilter类上加上@Component注解, * 另一种不添加这个注解,在config包下创建一个配置类config.WebConfig,通过配置Bean */ @Component public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("MyFilter.init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { System.out.println("time filter start"); long start = new Date().getTime(); filterChain.doFilter(request,response); System.out.println(new Date().getTime()-start); System.out.println("time filter end"); } @Override public void destroy() { System.out.println("MyFilter.destroy"); } }
第二种就是讲上面的注解去掉,在自定义config中用配置Bean的方式装配
package com.dayu.config; import com.dayu.filter.MyFilter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; /** * @author 大宇
Configuration注解配置很重要 */ @Configuration public class WebConfig { @Bean public FilterRegistrationBean timeFilter() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); MyFilter myFilter = new MyFilter(); registrationBean.setFilter(myFilter); ArrayList<String> urls = new ArrayList<>(); urls.add("/*");//配置过滤规则 registrationBean.setUrlPatterns(urls); return registrationBean; } }