SpringBoot中自定义注解进行登录校验

发布于 2023-02-13 | 作者: 朱哥哥你好呀 | 来源: CSDN博客 | 转载于: CSDN博客

1、自定义接口-LoginCheck

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginCheck {
    String value() default "";
}

2、自定义切面对象类-LoginCheckAspect

@Aspect
@Component
@SuppressWarnings("unused")
public class LoginCheckAspect{

    @Pointcut("@annotation(com.zhugege.miaosha1.annotation.LoginCheck)")
    private void pointcut(){};

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] params = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        if(params == null || args == null){
            throw new GlobleException(CodeMsg.MIAO_SHA_ERROR_NOT_LOGIN);
        }
        int index = -1;
        for(int i=0; i<args.length;i++){
            if(args[i] instanceof MiaoshaUser){
                index = i;
                break;
            }
        }
        if(index == -1 || args[index] == null){
            throw new GlobleException(CodeMsg.MIAO_SHA_ERROR_NOT_LOGIN);
        }
        return joinPoint.proceed(args);
    }
} 

3、需要登录验证的地方加上-@@LoginCheck(“登录检测”)

@RequestMapping(value = "/do_miaosha",method = RequestMethod.POST)
@ResponseBody
@LoginCheck("登录检测")
public Result miaosha(MiaoshaUser user, @RequestParam(value = "goodsId") long goodsId){
//未添加自定义注解需要对user进行判断 重复工作 
//        if(user == null){
//            throw new GlobleException(CodeMsg.MIAO_SHA_ERROR_NOT_LOGIN);
//        }
}