java过滤器(Filter)、Spring拦截器(Handler)
首先,tomcat容器中有Servlet容器和Spring容器,java过滤器。
- Filter 是在 Servlet 规范中定义的,是 Servlet 容器支持的;Handler是在 Spring 容器内的,是 Spring 框架支持的
- 方法的执行时机不一样:Filter是在Handler前执行的
- 不同的实现
@Component
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter 前置");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("Filter 处理中");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("Filter 后置");
}
}
Handler
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Interceptor 前置");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("Interceptor 处理中");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("Interceptor 后置");
}
}
接着将自定义好的拦截器处理类进行注册,并通过addPathPatterns
、excludePathPatterns
等属性设置需要拦截或需要排除的URL
。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
}
}
参考文章:
servlet容器,web容器,spring容器,springmvc容器的区别_万米高空的博客-CSDN博客_servlet springmvc区别
拦截器和过滤器的区别 - SegmentFault 思否