浅谈Tomcat Session管理分析

2019-10-18 19:52:32刘景俊

如果session已经存在,则直接返回;如果不存在则判定requestedSessionId是否为空,如果不为空则通过requestedSessionId到Session manager中获取session,如果为空,并且不是创建session操作,直接返回null;否则会调用Session manager创建一个新的session;

关于requestedSessionId是如何获取的,Tomcat内部可以支持从cookie和url中获取,具体可以查看CoyoteAdapter类的postParseRequest方法部分代码:

String sessionID;
if (request.getServletContext().getEffectiveSessionTrackingModes()
    .contains(SessionTrackingMode.URL)) {
 
  // Get the session ID if there was one
  sessionID = request.getPathParameter(
      SessionConfig.getSessionUriParamName(
          request.getContext()));
  if (sessionID != null) {
    request.setRequestedSessionId(sessionID);
    request.setRequestedSessionURL(true);
  }
}
 
// Look for session ID in cookies and SSL session
parseSessionCookiesId(req, request);

可以发现首先去url解析sessionId,如果获取不到则去cookie中获取,此处的SessionUriParamName=jsessionid;在cookie被浏览器禁用的情况下,我们可以看到url后面跟着参数jsessionid=xxxxxx;下面看一下parseSessionCookiesId方法:

String sessionCookieName = SessionConfig.getSessionCookieName(context);
 
for (int i = 0; i < count; i++) {
  ServerCookie scookie = serverCookies.getCookie(i);
  if (scookie.getName().equals(sessionCookieName)) {
    // Override anything requested in the URL
    if (!request.isRequestedSessionIdFromCookie()) {
      // Accept only the first session id cookie
      convertMB(scookie.getValue());
      request.setRequestedSessionId
        (scookie.getValue().toString());
      request.setRequestedSessionCookie(true);
      request.setRequestedSessionURL(false);
      if (log.isDebugEnabled()) {
        log.debug(" Requested cookie session id is " +
          request.getRequestedSessionId());
      }
    } else {
      if (!request.isRequestedSessionIdValid()) {
        // Replace the session id until one is valid
        convertMB(scookie.getValue());
        request.setRequestedSessionId
          (scookie.getValue().toString());
      }
    }
  }
}

sessionCookieName也是jsessionid,然后遍历cookie,从里面找出name=jsessionid的值赋值给request的requestedSessionId属性;

2.findSession查询session

获取到requestedSessionId之后,会通过此id去session Manager中获取session,不同的管理器获取的方式不一样,已默认的StandardManager为例:

protected Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();
 
public Session findSession(String id) throws IOException {
  if (id == null) {
    return null;
  }
  return sessions.get(id);
}

3.createSession创建session

没有获取到session,指定了create=true,则创建session,已默认的StandardManager为例: