自定义权限校验之annotation+reflection+interceptor邂逅

本文介绍了一种使用自定义注解、反射和拦截器实现权限校验的方法。通过创建自定义注解@Auth,结合Spring的HandlerInterceptorAdapter,实现了对特定方法的权限检查。示例代码展示了如何在控制器方法上应用注解,并通过WebMvcConfigurer添加拦截器完成权限验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

annotation+reflection+interceptor实现自定义权限校验
封装需准备如下:

  • 方法的注解:利用interceptor通过该方法注解进行权限校验
  • webMvcConfig配置类:添加interceptor拦截器
  • 权限校验拦截器类:对有注解的方法进行拦截,进行权限校验
  • controller类:进行测试
    代码示例:
/**
 * 自定义权限注解
 */
@Target({ElementType.METHOD,ElementType.TYPE})//作用范围为类或方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface Auth {
    //是否需要验证,true为校验,false为不校验
    //自定义注解+反射+拦截器 实现权限校验
    boolean key() default true;
}
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Auth auth = findAuthCheck(handlerMethod);
        // 若没有添加权限注解则直接跳过,允许访问
        if (auth == null) {
            return true;
        }
        // 获取权限注解中的值
        boolean key = auth.key();
        // 演示,若key为true则校验通过,否则不通过
        if (!key) {
            System.out.println("校验未通过");
            throw new RuntimeException("校验未通过");
        }
        return true;
    }

    private Auth findAuthCheck(HandlerMethod handlerMethod) {
        // 在方法上的注解
        // 通过反射获取
        Auth annotation = handlerMethod.getMethodAnnotation(Auth.class);
        if (annotation == null) {
            // 在类上的注解
            // 通过反射获取
            annotation = handlerMethod.getBeanType().getAnnotation(Auth.class);
        }
        return annotation;
    }

}
@Component
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor).addPathPatterns("/**");
    }
}
@RestController
public class DemoController {

    @RequestMapping("/hello")
    @Auth
    public Object hello() {
        return "已通过权限校验,顺利进入该方法";
    }

    @RequestMapping("/hello2")
    @Auth(key = false)
    public Object hello2() {
        return "已通过权限校验,顺利进入该方法";
    }

    @RequestMapping("/hello3")
    public Object hello3() {
        return "已通过权限校验,顺利进入该方法";
    }

}

已测试,结果符合预期
小结:注解是对java类的一种标注,通过拦截器对所有请求方法进行拦截,若方法上有注解标注则进行权限校验,需理解封装的设计模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值