使用自定义注解和AOP解决登录校验问题

1、如果每次都从Redis获取token,会有很多冗余代码

2、使用面向切面编程的思想

在不改变源代码或者很少改变源代码的情况下,增强类的某些方法。

在业务代码之前设置 切入点 

创建切面类,也就是比如登录校验的某些公共方法

切面类从切入点切入流程,形成切面

 

 2.1、创建注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogin {
    
}

2.2、创建切面类

进行token校验

/**
 * 切面类
 * @Author 伊人秋采唐
 * @Date 2024/8/10
 */
@Component //交给spring管理
@Aspect  //切面类  标识这是一个切面类
public class MyLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    //环绕通知,登录判断 Around
    //切入点表达式:指定对哪些规则的方法进行增强
    @Around("execution(* com.example.*.controller.*.*(..)) && @annotation(MyLogin)")
    public Object login(ProceedingJoinPoint proceedingJoinPoint, MyLogin myLogin)  throws Throwable {

        //1 获取request对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();//Spring提供的工具类
        ServletRequestAttributes sra = (ServletRequestAttributes)attributes;
        assert sra != null;
        HttpServletRequest request = sra.getRequest();

        //2 从请求头获取token
        String token = request.getHeader("token");

        //3 判断token是否为空,如果为空,返回登录提示
        if(!StringUtils.hasText(token)) {
            throw new MyException("");
        }

        //4 token不为空,查询redis
        String customerId = (String)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX+token);

        //5 查询redis对应用户id,把用户id放到ThreadLocal里面
        if(StringUtils.hasText(customerId)) {
            AuthContextHolder.setUserId(Long.parseLong(customerId));
        }

        //6 执行业务方法
        return proceedingJoinPoint.proceed();
    }

}

2.3、使用注解标识

表示这是一个切入点,在执行此方法之前,先执行切面方法

    @MyLogin
    @GetMapping("/getCustomerLoginInfo")
    public Result getCustomerLoginInfo() {

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伊人秋采唐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值