SpringBoot创建自定义注解跳过拦截器

开发过程中并不是所有接口都要验证登录的,对于不需要验证登录的控制器或方法需要定义一种能跳过拦截器的注解。

@Target(value = {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Uncontrol {
}

接着在拦截器的preHandle方法内,在验证登录的逻辑处理前添加如下代码

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Uncontrol uncontrolAnnotation = handlerMethod.getMethodAnnotation(Uncontrol.class);
            if (Objects.nonNull(uncontrolAnnotation)) {
                System.out.println("Method @Uncontrol");
                return true;
            }

            Class<?> clazz = handlerMethod.getBeanType();
            if (Objects.nonNull(AnnotationUtils.findAnnotation(clazz, Uncontrol.class))) {
                System.out.println("Class @Uncontrol");
                return true;
            }
        }
        logger.info("验证用户登录情况");
        //验证用户登录的逻辑部分
        return true;
    }

然后给不需要拦截的方法或类加上@Uncontrol注解,拦截器就会放行此方法或类

加在方法上是不拦截此方法,加在类上是不拦截此类中所有方法,方法的注解优先。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值