1:编写一个类 实现 HandlerInterceptor接口
@Componentpublic class TestInterceptor implements HandlerInterceptor { //前置方法 进入controller之前执行 可用于校验token权限 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //controller执行之前,进行拦截的业务代码
return true;//放行 }
//后置方法 controller执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
//视图渲染后执行方法 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2:注册拦截器到spring容器
编写一个配置类,实现WebMvcConfigurer接口
/** * springboot将拦截器注入spring容器 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private TestInterceptor testInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //拦截器拦截所有路径 registry.addInterceptor(testInterceptor).addPathPatterns("/**"); } }