今天看到项目中有拦截器和过滤器,就比较好奇这两者的区别。
先上图,最直观的感受是Filter是在servlet的外层,而Interceptor是在Servlet的内层,当然没有这么简单。
Filter和Interceptor的区别
- Filter是Servlet规范规定的,只能用于Web程序中。而Interceptor可以用于多种程序。
- Filter是servlet容器支持,Interceptor是spring容器支持
- Interceptor是spring的组件,可以使用spring中的任何资源,对象,而Filter不行
- Filter只能在Servlet前后起作用,拦截器能深入到方法前后。在spring构建的程序中,优先使用拦截器
- Filter是基于函数回调,Interceptor是基于Java反射的。
Filter使用
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new XssFilter());
registration.addUrlPatterns("/*");
registration.setName("xssFilter");
registration.setOrder(1);
return registration;
}
}
public class XssFilter implements Filter{
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
}
@Override
public void destroy() {
}
}
Interceptor使用
@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return super.preHandle(request, response, handler);
}
}
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private SessionInterceptor sessionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(sessionInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/XXXXXX.json");
}
}