两种优雅的获取当前登录用户ID的方式

目录

方式一:通过 HttpServletRequest 取请求头中 的token 进行转化

方式二:通过线程本地变量 ThreadLocal


方式一:通过 HttpServletRequest 取请求头中 的token 进行转化

HttpServletRequest 可以@Autowired 注入进来,或者作为Controller里的参数。

//从请求头中拿token
String token = request.getHeader("token");
//用JwtUtil工具 根据 盐 解析token,得到当时放进去的map
Map claims = JwtUtil.parseJWT("salt", token);
//取出map里的userId
Long userId= Long.valueOf(claims.get("userId").toString());

方式二:通过线程本地变量 ThreadLocal

先写一个工具类 BaseContext

public class BaseContext{

    //创建线程本地变量
    public static final ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    //set值
    public static void setCurrentId(Long id){
        threadLocal.set(id);
    }

    //取值
    public static Long getCurrentId{
        return threadLocal.getCurrentId();
    }

    //删除
    public static void removeCurrentId() {
        threadLocal.remove();
    }
}

在合适的地方,把值塞进去。比如jwt令牌认证通过之后。

BaseContext.setCurrentId(userId);

在需要的地方,从线程本地变量里取值,就可以了。

Long userId = BaseContext.getCurrentId;

个人感觉这种方式更优雅。

猜你喜欢

转载自blog.csdn.net/tomorrow9813/article/details/131736382