正常来说,我们自定义拦截器Filter是需要@Component注解让我们的拦截器注入Bean,从而让拦截器生效。当需要第三方Filter的时候,我们可以不需要使用@Component注解,从而使用它。
一般使用Filter,(ps:下面这样使用的话他是对所有的路径都进行过滤的。)
package com.yhn.web.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
import java.util.Date;
/**
* 自定义过滤器
* Created by yhn on 2017/12/3
*/
//@Component
//如果注解Component不在则当作第三方拦截器使用 在 com.yhn.web.config.WebConfig
public class TimeFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("time filter 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 finish");
}
@Override
public void destroy() {
System.out.println("time filter destroy");
}
}
而对使用第三方Filter通过配置Bean导入项目(与写xml效果相同)
SpringBoot的出现就是为了简化配置文件xml。
package com.yhn.web.config;
import com.yhn.web.filter.TimeFilter;
import com.yhn.web.interceptor.TimeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by yhn on 2017/12/3.
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
private TimeInterceptor timeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timeInterceptor);
}
@Bean
public FilterRegistrationBean timeFile(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimeFilter timeFilter = new TimeFilter();
registrationBean.setFilter(timeFilter);
List<String> url = new ArrayList<>();
url.add("/*"); //对所有路径起作用。对项目来说看其所需
registrationBean.setUrlPatterns(url);
return registrationBean;
}
}