拦截器和过滤器之间的区别是什么?
自定义拦截器
1. 创建拦截器类:让类实现HandlerInterceptor接口,重写接口中的三个方法
@Component //定义拦截器类,实现HandlerInterceptor接口 public class ProjectInterceptor implements HandlerInterceptor { @Override //原始方法调用前执行的内容 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle..."); return true; } @Override //原始方法调用后执行的内容 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle..."); } @Override //原始方法调用完成后执行的内容 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion..."); } }
2. 配置拦截器类:在WebMvcConfigurer
中注册该拦截器,并告诉spring
哪些路径需要拦截,哪些路径不需要拦截
@Configuration public class InterceperConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器 InterceptorRegistration interceptorRegistration = registry.addInterceptor(new ProjectInterceptor()); //如下的路径不拦截,多个路径用逗号分隔 interceptorRegistration.excludePathPatterns("/demo/test2"); //拦截如下路径 interceptorRegistration.addPathPatterns("/**"); } }
2.1. 配置多个拦截器
拦截器的运行顺序
标签:Exception,拦截器,Java,路径,HttpServletResponse,Override,Interceptor,public From: https://www.cnblogs.com/ShengLiu/p/17694844.html