HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession session = request.getSession();
通过getSession()方法可以获取当前的HttpSession对象。
HttpSession是一个接口,具体实现类有HtmlUnitMockHttpSession,MockHttpSession,StandardSession和StandardSessionFacade
阅读StandardSession类
public String getId() {
return this.id;
}
方法返回当前session的id值,是一个字符串protected String id = null;
HttpServletRequest的通过getSession()方法,点击进入查看,在Request这个具体实现类里面
public HttpSession getSession() {
Session session = this.doGetSession(true);
return session == null ? null : session.getSession();
}
进入protected Session doGetSession(boolean create)方法,关键代码是Context context = this.getContext();
获取上下文context,然后从中获取Manager对象,Manager manager = context.getManager();
public interface Context extends Container, ContextBind {
String ADD_WELCOME_FILE_EVENT = "addWelcomeFile";
String REMOVE_WELCOME_FILE_EVENT = "removeWelcomeFile";
String CLEAR_WELCOME_FILES_EVENT = "clearWelcomeFiles";
String CHANGE_SESSION_ID_EVENT = "changeSessionId";
context继承自Container,说明context是由容器进行管理(tomcat)
public abstract class ManagerBase extends LifecycleMBeanBase implements Manager
在ManagerBase中,
public Session findSession(String id) throws IOException {
return id == null ? null : (Session)this.sessions.get(id);
}
而这个session是存在一个ConcurrentHashMap中的
protected Map<String, Session> sessions = new ConcurrentHashMap();
session是这样存进map的
public void add(Session session) {
this.sessions.put(session.getIdInternal(), session);
int size = this.getActiveSessions();
if (size > this.maxActive) {
synchronized(this.maxActiveUpdateLock) {
if (size > this.maxActive) {
this.maxActive = size;
}
}
}
}
而getId()和getIdInternal()其实都是返回的session的id,一个字符串而已。
public String getId() {
return this.id;
}
public String getIdInternal() {
return this.id;
}