Two elegant ways to get the currently logged in user ID

Table of contents

Method 1: Get the token in the request header through HttpServletRequest for conversion

Method 2: Through the thread local variable ThreadLocal


Method 1: Get the token in the request header through HttpServletRequest for conversion

HttpServletRequest can be injected into @Autowired, or as a parameter in the 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());

Method 2: Through the thread local variable ThreadLocal

First write a tool class 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();
    }
}

Where appropriate, tuck in the value. For example, after the jwt token authentication is passed.

BaseContext.setCurrentId(userId);

Where needed, get the value from the thread local variable, and that's it.

Long userId = BaseContext.getCurrentId;

Personally, I feel this way is more elegant.

Guess you like

Origin blog.csdn.net/tomorrow9813/article/details/131736382