欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用ThreadLocal存储Session,方便其他地方调用用户信息

程序员文章站 2022-05-07 23:28:04
...

 

package com.urt.core.web;

import javax.servlet.http.HttpSession;

import com.urt.core.authority.entity.User;

/** 
 * 用户Session存储器,方便在Controller层以外获取用户
 * @author happyqing
 * @date 2015-4-25
 */
public class UserSession {
	private static final ThreadLocal<HttpSession> userSession = new ThreadLocal<HttpSession>();
	
	public static void setUserSession(HttpSession session) {
		userSession.set(session);
    }
  
    public static HttpSession getUserSession() {
        return userSession.get();
    }
    
    public static User getUser(){
		return (User)userSession.get().getAttribute("user");
	}
    
    public static void setAttribute(String key, Object value){
    	userSession.get().setAttribute(key, value);
	}
    
    public static Object getAttribute(String key){
    	return userSession.get().getAttribute(key);
	}

}