基于拦截器,判断请求是否为动态请求(即访问控制层)

@Component
@Slf4j
public class JwtTokenUserInterceptor implements
        HandlerInterceptor {
@Autowired
private JwtProperties jwtProperties;
/**
* 校验jwt
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的⽅法还是其他资源
    if (!(handler instanceof HandlerMethod)) {
        //当前拦截到的不是动态⽅法,直接放⾏
        return true;
    }
    //1、从请求头中获取令牌
    String token = request.getHeader(jwtProperties.getUserTokenName());
    //2、校验令牌
    try {
        log.info("jwt校验:{}", token);
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        log.info("当前⽤户的id:", userId);
        BaseContext.setCurrentId(userId);
        //3、通过,放⾏
        return true;
    } catch (Exception ex) {
        //4、不通过,响应401状态码
        response.setStatus(401);
        return false;
    }
}
}

Object handler 是 Spring 拦截器(Interceptor)中的一个参数,用于表示当前被拦截的处理器(handler)。在这段代码中,handler 参数表示当前拦截到的处理器对象。

在 Spring MVC 中,处理器可以是控制器(Controller)的方法,也可以是其他资源,如静态资源。通过判断 handler 是否是 HandlerMethod 的实例,可以确定当前拦截到的是否是一个动态方法(即控制器的方法)。

如果 handler 不是 HandlerMethod 的实例,意味着当前拦截到的不是控制器的方法,可能是其他资源,比如静态资源。在这种情况下,代码直接返回 true,表示放行,继续执行后续的拦截器或处理器链。

如果 handler 是 HandlerMethod 的实例,则表示当前拦截到的是一个控制器的方法,需要进行进一步的处理,如校验令牌、设置上下文等。

/**
 * 配置类,注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/employee/login");
    }
}

1:编写拦截器

2:注册拦截器

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值