public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String loginId = request.getHeader("loginId");
if (StringUtils.isNotBlank(loginId)) {
LoginContextHolder.set("loginId", loginId);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
LoginContextHolder.remove();
}
}
public class LoginContextHolder {
private static final InheritableThreadLocal<Map<String,Object>> THREAD_LOCAL =
new InheritableThreadLocal<Map<String, Object>>();
public static void set(String key,Object val){
Map<String,Object> map = getThreadLocalMap();
map.put(key,val);
}
public static Object get(String key){
Map<String, Object> threadLocalMap = getThreadLocalMap();
return threadLocalMap.get(key);
}
public static void remove(){
THREAD_LOCAL.remove();
}
public static String getLoginId(){
return String.valueOf(getThreadLocalMap().get("loginId"));
}
public static Map<String,Object> getThreadLocalMap(){
Map<String, Object> map = THREAD_LOCAL.get();
if(Objects.isNull(map)){
map = new ConcurrentHashMap<>();
THREAD_LOCAL.set(map);
}
return map;
}
}