SpringBoot——HandlerInterceptor(登录拦截器)

1.建立LoginInterceptor实现接口HandlerInterceptor

@Slf4j  // => log
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("当前路径:"+uri);
        String token = request.getHeader(QcbyConstant.TOKEN);
        String contentType = request.getHeader("Content-Type");
        log.info("contentType:"+contentType);

        String userId = JwtUtil.getAudience(token);
        if (!JwtUtil.verifyToken(token,userId)) {
             //jwt中的验证token
            // 未通过拦截器验证,抛出异常
            log.error("登录失败!");
            throw new RuntimeException("登录失败!");
        }
   
//权限验证,需要自定义注解
       if (!(handler instanceof  HandlerMethod)){
            //不是接口请求不拦截
            return  true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        RequestMapping requestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);

        List<String> authStrList = userService.getAuthStrListByUserId(Long.valueOf(userId));
          //添加了自定义注解的方法
        PreAuth preAuth = handlerMethod.getMethodAnnotation(PreAuth.class);
        log.info("preAuth:"+preAuth);
        if(!authStrList.contains(preAuth.value())){
            // 用户无权限访问
            log.error("用户无权限访问!");
            throw new RuntimeException("用户无权限访问!");

        }
        // 有权限访问
        return true;
    }
}

1.preHandle方法是controller方法执行前拦截的方法

  • 可以使用request或者response跳转到指定的页面
  • return true放行,执行下一个拦截器,如果没有拦截器,执行controller中的方法。
  • return false不放行,不会执行controller中的方法。

2.postHandle是controller方法执行后执行的方法,在JSP视图执行前。

  • 可以使用request或者response跳转到指定的页面
  • 如果指定了跳转的页面,那么controller方法跳转的页面将不会显示。
  • postHandle方法是在JSP执行后执行

3.afterCompletion是controller跳转的jsp页面都执行完成了,最后执行该方法;

  • request或者response不能再跳转页面了

2.重点:如果不是controller方法直接通过

  if (!(handler instanceof  HandlerMethod)){
            //不是接口请求不拦截
            return  true;
        }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值