1、拦截器
1、HandlerInterceptor
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("preHandle拦截的请求路径是{}",requestURI);
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser != null){
return true;
}
request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle执行{}",modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion执行异常{}",ex);
}
}
2、配置拦截器
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");
}
}
3、拦截器原理
- 根据当前请求,找到HandlerExecutionChain【可以处理请求的handler以及handler的所有拦截器】
- 先来顺序执行所有拦截器的preHandle方法
- 如果当前拦截器的prehandle返回为true,则执行下一个拦截器的preHandle。
- 如果当前拦截器返回为false,直接 倒序执行所有已经执行了的拦截器的 afterCompletion
- 如果任何一个拦截器返回的是false。直接跳出目标方法
- 所有拦截器都返回true,执行目标方法
- 倒序执行所有拦截器的postHandle方法
- 前面的步骤有任何异常都会直接倒序触发afterCompletion
- 页面成功渲染完成以后,也会倒序触发afterCompletion
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/23be856b9fcea652e14d0d6b8ef57c71.png#pic_center)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cc8d7f25b886a525ee4b1f957f828a11.png#pic_center)