赞
踩
- /**
- * 登录检查
- * 1、配置好拦截器要拦截哪些请求
- * 2、把这些配置放在容器中
- */
- @Slf4j
- public class LoginInterceptor implements HandlerInterceptor {
-
- /**
- * 目标方法执行之前
- * @param request
- * @param response
- * @param handler
- * @return
- * @throws Exception
- */
- @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","请先登录");
- // re.sendRedirect("/");
- request.getRequestDispatcher("/").forward(request,response);
- return false;
- }
-
- /**
- * 目标方法执行完成以后
- * @param request
- * @param response
- * @param handler
- * @param modelAndView
- * @throws Exception
- */
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
- log.info("postHandle执行{}",modelAndView);
- }
-
- /**
- * 页面渲染以后
- * @param request
- * @param response
- * @param handler
- * @param ex
- * @throws Exception
- */
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- log.info("afterCompletion执行异常{}",ex);
- }
- }
- /**
- * 1、编写一个拦截器实现HandlerInterceptor接口
- * 2、拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
- * 3、指定拦截规则【如果是拦截所有,静态资源也会被拦截】
- */
- @Configuration
- public class AdminWebConfig implements WebMvcConfigurer {
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new LoginInterceptor())
- .addPathPatterns("/**") //所有请求都被拦截包括静态资源
- .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求
- }
- }
1、根据当前请求,找到HandlerExecutionChain【可以处理请求的handler以及handler的所有 拦截器】
2、先来顺序执行 所有拦截器的 preHandle方法
3、如果任何一个拦截器返回false。直接跳出不执行目标方法
4、所有拦截器都返回True。执行目标方法
5、倒序执行所有拦截器的postHandle方法。
6、前面的步骤有任何异常都会直接倒序触发 afterCompletion
7、页面成功渲染完成以后,也会倒序触发 afterCompletion
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。