第一步:定义工具类,将需要的信息写入线程池,本例将session中的usrid放入线程池
package com.itheima.reggie.common;
/**
* Created with IntelliJ IDEA.
* User: Hzy
* Date: 2022/4/13
* Time: 15:14
*/
/**
* 基于ThreadLocal封装的工具类,用于保存和获取当前登录用户的id
*/
public class BaseContext {
private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
/**
* 设置值
* @param id
*/
public static void setCurrentId(Long id){
threadLocal.set(id);
}
/**
* 获取值
* @return
*/
public static Long getCurrentId(){
return threadLocal.get();
}
}
第二步,在能够获取session的地方(比如自定义的登陆拦截器,或者Controller中),调用
BaseContext.setCurrentId(empId);
Long empId = (Long) request.getSession().getAttribute("employee");
BaseContext.setCurrentId(empId);
第三步,在需要使用session中userid的地方,调用BaseContext.getCurrentId();
三个步骤必须确保在同一线程ID上
828

被折叠的 条评论
为什么被折叠?



