目录

SpringBoot之拦截器优雅实现登录权限拦截

目录

http://image.catbro.cn/bc1674bfaace4.png


  • 在上一章节中我们讲解了Spring Boot中拦截器的基本使用步骤

  • 本次我们将使用拦截器来实现 登录状态的拦截判断需求

  • OK,直接上代码:

  • 首先我们实现一个AdminLoginInterInterceptor 拦截器,在用户访问管理端的url时,判断是否为管理员

      @Component
      public class AdminLoginInterceptor implements HandlerInterceptor {
          public static String LOGIN_FLAG = "admin";
          private void printMsg(String msg) {
              System.out.println("[AdminLoginInterceptor] " +msg);
    
          }
    
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              printMsg("preHandle");
    
              HttpSession session = request.getSession(true);
              if (session.getAttribute(LOGIN_FLAG) != null) {
                  printMsg("已登录");
                  return true;
              }
              // 重定向到登录页面
              response.sendRedirect(Utils.getHostPath(request) + "/admin/loginPage");
              return true;
          }
          @Override
          public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 ModelAndView modelAndView) throws Exception {
              printMsg("postHandle");
          }
    
          @Override
          public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                      Object handler, Exception exception) throws Exception {
              printMsg("afterCompletion");
    
          }
      }
    
  • 拦截器写好了,此时就是要将我们的拦截器与Spring关联上并告知 如何调用了

  • 通过实现一个WebMvcConfigurer,然后通过addInterceptors方法参数中的注册器注册拦截器

      @Component
      public class ProductServiceInterceptorAppConfig implements WebMvcConfigurer {
         @Autowired
         PathInterceptor pathInterceptor;
    
         @Autowired
         AdminLoginInterceptor adminLoginInterceptor;
    
         @Override
         public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**")
                    .excludePathPatterns("/admin/login","/admin/loginPage");
    
         }
      }
    
  • 在login的时候我们将登陆成功后的信息存入session中 通过LOGIN_FLAG作为key即可