三种添加方式
1 实现Filter 添加@Component注解,此方式过滤所有url,可以在代码中判断过滤那些
@Component
@Order(1) //优先级,最顶级
public class TimeFilter implements Filter {
@Override
public void destroy() {
System.out.println("time filter destroy");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("time filter start");
long start = new Date().getTime();
String url = request.getRequestURL().toString();
if (url.contains("XXX")) {
//过滤逻辑
......
} else {
//不过滤
filterChain.doFilter(servletRequest, servletResponse);
}
chain.doFilter(request, response);
System.out.println("time filter 耗时:"+ (new Date().getTime() - start));
System.out.println("time filter finish");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("time filter init");
}
}
2 @Configuration 配置类中通过 FilterRegistrationBean 注册 ,可以配置过滤url 、配置优先级
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean timeFilter() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimeFilter timeFilter = new TimeFilter();
registrationBean.setFilter(timeFilter);
List<String> urls = new ArrayList<>();
urls.add("/*"); // 可以配置过滤url
registrationBean.setUrlPatterns(urls);
registrationBean.setOrder(1);//优先级,最顶级
return registrationBean;
}
}
3 通过 @WebFilter 添加过滤器,可以配置过滤url 、配置优先级
@WebFilter(urlPatterns = "/*") //可以配置过滤url
@Order(1) //优先级,最顶级
public class TimeFilter implements Filter {
@Override
public void destroy() {
System.out.println("time filter destroy");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("time filter start");
long start = new Date().getTime();
chain.doFilter(request, response);
System.out.println("time filter 耗时:"+ (new Date().getTime() - start));
System.out.println("time filter finish");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("time filter init");
}
}