【SpringBoot】自定义注解+拦截

发布时间 2023-03-22 21:08:47作者: Hello霖

 

创建一个注解,用来校验身份

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

//    int user();
    // 管理员
//    String User_ADMIN = "101";
//    // 普通用近乎
//    String User_STANDARD = "102";
//    // 被封禁
//    String User_LOCK = "500";


}

@Target({ElementType.TYPE,ElementType.METHOD})  让注解可用在类或方法上

 

 

 

拦截器中捕获注解【这里用webmvc的】HandlerInterceptor接口    preHandle  拦截请求

 

private boolean checkAdmin(HttpServletRequest request, Object handler,String token)  {
    // 如果不是方法
    if (!(handler instanceof HandlerMethod)){
        return true;
    }

    // 获取注解
    AuthUser pl = ((HandlerMethod)handler).getMethodAnnotation(AuthUser.class);//写在方法上的
    AuthUser annotation = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(AuthUser.class);//写在类上的

    if(annotation != null){
        System.out.println("获取到写在类上注解了");
    }


    if(pl != null){
        System.out.println("获取到写在方法上的注解了");
    }
    
    
        return true;
}