一、自定义拦截器实现步骤
1、创建拦截器类并实现HandlerInterceptor接口
2、创建SpringMVC自定义配置类,实现WebMvcConfigurer接口中addInterceptors方法
3、将自定义拦截器类加入配置类
二、代码实现
自定义拦截器类:
public class MyInterceptor1 implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor1 -> preHandle执行了"); //true表示继续执行 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor1 -> postHandle 执行了"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor1 -> afterCompletion 执行了"); } }
配置类:
@Configuration public class MVCConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //addPathPatterns添加拦截路径 //excludePathPatterns添加不拦截路径 registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/test1/**").excludePathPatterns("/test2"); } }
创建控制器进行测试:
@RestController public class InterceptorController { @RequestMapping("/test1/{name}") public String test1(@PathVariable("name") String name) { return "hi, " + name; } @RequestMapping("/test2") public String test2() { return "test2"; } }
输入localhost:8080/test2
控制台无输出即表示没有拦截
输入localhost:8080/test1/jack
控制台输出: