ThreadLocal取代每次都从session中获取登录用户信息




方式一:直接使用JDK中ThreadLocal方式

1.先定义一个存放登录用户信息的实体类,并在这里面操纵用户信息

public class UserContext implements Serializable{

    private static ThreadLocal<LoginEntity> loginEntityThreadLocal=new ThreadLocal<>();

    public static LoginEntity getUserSession() {
        return loginEntityThreadLocal.get();
    }

    public static void setUserSession(LoginEntity entity) {
        loginEntityThreadLocal.set(entity);
    }

    public static void removeUserSession() {
        loginEntityThreadLocal.remove();
    }
}
2.在过滤其中进行存放用户登录信息
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		response.addHeader("Access-Control-Allow-Origin","*");
		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,X-Pagination");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.addHeader("Access-Control-Expose-Headers", "X-Pagination");
		
		//System.out.println(session.getId());
		if (isInclude(request.getServletPath())) {
			LoginEntity loginEntity = (LoginEntity) session.getAttribute(Const.LOGINED_KEY);
			if (loginEntity != null) {
				UserContext.setUserSession(loginEntity);
				chain.doFilter(request, response);
			} else {
				unLogin(response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

方式二:RequestContextHolder是Spring中对ThreadLocal进行了封装

1.先定义一个存放登录用户信息的实体类,并在这里面操纵用户信息

public class UserContext implements Serializable{
    
    /**
     * 获取当前线程绑定的用户登录对象
     *
     * @return
     */
    public static LoginEntity getUserSession() {
        return (LoginEntity) RequestContextHolder.getRequestAttributes().getAttribute(Constant.LOGINED_KEY,  RequestAttributes.SCOPE_REQUEST);
    }

    /**
     * 将用户登录对象绑定到当前线程
     *
     * @param loginEntity
     */
    public static void setUserSession(LoginEntity loginEntity) {
        RequestContextHolder.getRequestAttributes().setAttribute(Constant.LOGINED_KEY, loginEntity, RequestAttributes.SCOPE_REQUEST);
    }

    /**
     * 将用户登录对象从当前线程销毁
     */
    public static void removeUserSession() {
        RequestContextHolder.getRequestAttributes().removeAttribute(Constant.LOGINED_KEY,RequestAttributes.SCOPE_REQUEST);
    }

}

2.在过滤其中进行存放用户登录信息
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		response.addHeader("Access-Control-Allow-Origin","*");
		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,X-Pagination");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.addHeader("Access-Control-Expose-Headers", "X-Pagination");
		
		//System.out.println(session.getId());
		if (isInclude(request.getServletPath())) {
			LoginEntity loginEntity = (LoginEntity) session.getAttribute(Const.LOGINED_KEY);
			if (loginEntity != null) {
				UserContext.setUserSession(loginEntity);
				chain.doFilter(request, response);
			} else {
				unLogin(response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}


  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
用户信息保存到ThreadLocal是通过将用户信息存储在ThreadLocal的value实现的。具体来说,我们可以使用一个自定义的ThreadLocal类,在其设置put()方法将用户信息存储到ThreadLocal的value,使用get()方法获取用户信息,使用remove()方法在使用完用户信息后将其从ThreadLocal删除,以避免内存泄漏的风险。例如,在一个名为UserThreadLocal的类,我们可以定义put()、get()和remove()方法来实现用户信息的保存和获取。通过调用put()方法将用户信息存储在ThreadLocal,然后在需要使用用户信息的地方调用get()方法获取用户信息。最后,在合适的时机,例如在登录拦截器的afterCompletion()方法,使用remove()方法将ThreadLocal用户信息删除,以免造成内存泄漏。这样可以保证在同一个线程,多个地方都能够方便地获取到相同的用户信息,而不会相互干扰。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ThreadLocal存储用户登录信息](https://blog.csdn.net/weixin_46000937/article/details/126828778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [ThreadLocal实现登录(保存用户登录信息)](https://blog.csdn.net/qq_56851614/article/details/125464270)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值