可根据需要实现三个方法中的一个或多个
preHandle是在controller前执行,这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会向下执行,postHandle在业务处理器处理请求执行完成后,生成视图之前执行,afterCompletion在DispatcherServlet完全处理完请求后被调用,可用于清理资源等 。
public class MyInterceptor 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"); } } 复制代码
@RestController public class TestController { @GetMapping(value = "/hello") public String hello() { System.out.println("hello controller"); return "hello world"; } @GetMapping(value = "/test") public String test() { System.out.println("test controller"); return "this is test"; } } 复制代码
实现接口方法addInterceptors,registry.addInterceptor是添加一个拦截器,addPathPatterns()是添加要拦截的路径,excludePathPatterns是添加不拦截的路径
@Configuration public class MyConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 添加拦截器 InterceptorRegistration interceptorRegistration = registry.addInterceptor(new MyInterceptor()); // interceptorRegistration.addPathPatterns("/**") .excludePathPatterns("/test"); } } 复制代码浏览器访问
,控制台输出