**
* @Auther: Jhon Li
* @Date: 2018/12/20 11:51
* @Description: 过滤器 spring自己的可以用 component注解 来注入,如果是第三方就需要从新 通过 配置类来注入,config中
*
* 缺点 :可以拿到http请求的原始信息,但是拿不到真正处理这个请求的方法信息
*/
//@Component 这个注解式全部路径过滤
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("time filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("time filter start");
long time = new Date().getTime();
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("time filter :"+(new Date().getTime()-time));
System.out.println("time filter finish");
}
@Override
public void destroy() {
System.out.println("time filter destroy");
}
}
也可以在配置类注入
/**
* @Auther: Jhon Li
* @Date: 2018/12/20 12:04
* @Description:
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
private TimeInterceptor timeInterceptor;
//添加拦截器到配置中
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(timeInterceptor);
}
// @Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
TimeFilter timeFilter=new TimeFilter();
filterRegistrationBean.setFilter(timeFilter);
List<String> urls=new ArrayList<>();
urls.add("/**"); //指定那些url 过滤
filterRegistrationBean.setUrlPatterns(urls);
return filterRegistrationBean;
}
}