1.创建一个拦截器类实现HandlerInterceptor接口,重写其中的3个方法,这拦截器中方法的执行顺序为:preHandle--Controller--postHandle--afterCompletion,只有preHandle返回true,才会继续向下执行,多个拦截器形成拦截器链,如果第一个preHandle返回false,则后面的方法都不会执行。
public class MyInterceptor1 implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ System.out.println("MyInterceptor1>>>preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){ System.out.println("MyInterceptor1>>>postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){ System.out.println("MyInterceptor1>>>afterCompletion"); } }
2.配置拦截器
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) {
//拦截器名 registry.addInterceptor(new MyInterceptor1()) //拦截路径
.addPathPatterns("/**") //排除路径
.excludePathPatterns("/hello"); } }
3.controller·
@RestController public class HelloController { @GetMapping("/hello") public String hello() { return "hello"; } @GetMapping("/hello2") public String hello2() { return "hello2"; } }
则没有被拦截,被排除在外