首先新建config包下的MvcConfig类
@Configuration//配置类 spring-xxx.xml
public class MvcConfig implements WebMvcConfigurer {
//<bean></bean>
@Bean
public LoginInterceptor loginInterceptor(){
return new LoginInterceptor();
}
// 添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor()).addPathPatterns("/*");
}
}
controller层新建一个跳转方法用于拦截
@RestController
public class HelloController {
@GetMapping("say")
public String say(){
System.out.println("say");
return "hello";
}
}
新建interceptor包下的LoginInterceptor
//拦截器
public class LoginInterceptor 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");
}
}
最终结果,依次打印
如果prehandler返回的是false
say方法会被拦截,并不会打印