owo
- Spring Boot 定义了HandlerInterceptor接口来实现自定义拦截器的功能
- HandlerInterceptor接口定义了preHandle、postHandle、afterCompletion三种方法
- 前端请求经过preHandle逐层调入控制器(从浅到深)
- 控制器的响应依次调用postHandle方法返回(从深到浅)
- 页面渲染完毕之后依次调用afterCompletion方法(从深到浅)
拦截器的定义
就是一个实现了 HandlerInterceptor
接口的类
com.hxy.helloworld/interceptor/LoginInterceptor.java
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
System.out.println("LoginInterceptor");
return true;
}
}
拦截器的注册
只定义没用,需要配置里注册
com.hxy.helloworld/config/Webconfig.java
可以指定拦截路径
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
.addInterceptor(new LoginInterceptor());
registry//registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**");
}
}