场景需求 : 虽然在登录之后,前端可以获取到我所返回的jwt,然后通过它保持登录状态和获取信息。然后在调用接口的时候将信息传递给我进行各种操作。
但是种种原因问题,我需要很简便地在执行操作的过程中,在任何一个方法中都能获取到当前用户的一些基本信息。
而不纯粹依赖前端传值。
因为并非所有方法都可以拿到jwt,如果没有请求头作为参数的话。
我设想了一种简便的实现方式,就是在请求通过jwtFilter的时候,获取jwt的同时,把解析出来的用户信息存储到ThreadLocal之中。
使用ThreadLocal的话,可以在用户调用的过程中任何方法里作为一个全局的参数,随时得到想要的信息。
1、登陆成功后把用户信息存储到redis缓存中
伪代码如下
@RequestMapping("/login")
public Map<String,String> login(String name){
Map<String,Object> result = new HashMap<>();
result.put(ExecutionContext.USER_ID,name);
result.put(ExecutionContext.USER_NAME,name);
result.put(ExecutionContext.ACCESS_TOKEN,name);
//存储用户信息到redis中 key值Token value是用户信息
RMap<String, String> map = redissonClient.getMap(name);
map.put(ExecutionContext.USER_ID,name);
map.put(ExecutionContext.USER_NAME,name);
map.put(ExecutionContext.ACCESS_TOKEN,name);
return map;
}
2.在拦截器中进行存放用户登录信息
伪代码如下
package com.ahies.zgstm.interceptor;
import com.ahies.zgstm.common.anno.NoNeedLogin;
import com.ahies.zgstm.common.anno.NoValidPrivilege;
import com.ahies.zgstm.constant.InterceptorConstant;
import com.ahies.zgstm.module.synthesizes.sys.service.UserService;
import com.ahies.zgstm.util.ExecutionContext;
import com.ahies.zgstm.util.PmsStringUtils;
import com.ahies.zgstm.util.ResponseResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @Description [ 登录拦截器 ]
* @Date 2020/7/21 11:15
* @Author zsj
*/
@Co