/** * 自定义拦截器 **/ @Configuration//声明这是一个拦截器 public class MyInterceptor extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { HandlerInterceptor interceptor = new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("自定义拦截器......"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } };
//添加到registry里 并设置要拦截的路径 “/**”表示全部拦截 registry.addInterceptor(interceptor).addPathPatterns("/**"); } }