首先我们创建Interceptor,实现HandlerInterceptor覆写方法:
一、下面我创建了三个拦截器:
MyInterceptor,UserInterceptor,StudentInterceptor
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("MyInterceptor preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("MyInterceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("MyInterceptor afterCompletion");
}
}
@Component
public class StudentInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("StudentInterceptor preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("StudentInterceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("StudentInterceptor afterCompletion");
}
}
@Component
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("UserInterceptor preHandle");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("UserInterceptor postHandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("UserInterceptor afterCompletion");
}
}
@Configuration
public class MyAdapter implements WebMvcConfigurer {
@Resource
private MyInterceptor myInterceptor;
@Resource
private UserInterceptor userInterceptor;
@Resource
private StudentInterceptor studentInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//1.加入的顺序就是拦截器执行的顺序,
//2.按顺序执行所有拦截器的preHandle
//3.所有的preHandle 执行完再执行全部postHandle 最后是postHandle
registry.addInterceptor(studentInterceptor).addPathPatterns("/**");
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
registry.addInterceptor(userInterceptor).addPathPatterns("/**");
}
}
@RestController
public class TestController {
@RequestMapping("/test")
public String test() {
return "test";
}
}
registry.addInterceptor(customInterceptor2).order(1) registry.addInterceptor(customInterceptor1).order(2)
当引入其他jar时,可能也会有用到拦截器,根据业务这样写指定顺序应该更合理吧