Java 服务器和客户端的 session 是怎么实现的?

来自姬鸿昌的知识库
跳到导航 跳到搜索

在 Java 中,session 是通过在服务器端创建一个唯一的标识符(通常是一个字符串)来实现的。当用户与服务器建立会话时,服务器将创建一个与该用户相关联的新 session,并将 session 标识符返回给客户端。

客户端在之后的请求中将发送该 session 标识符作为 cookie 或请求参数。服务器使用该标识符来检索与该用户相关联的 session,并在需要时将相关信息存储在该 session 中。

Java 中的 session 通常使用 Servlet API 中的 HttpSession 接口来实现。该接口提供了一组方法,用于操作 session 中存储的数据。在 Servlet 中,可以使用 request.getSession() 方法获取当前请求的 session。

服务端是怎么把 session 标识符放到客户端的 cookie 中的?

在 Java 中,服务器通常会将 session 标识符存储在客户端的 cookie 中。这可以通过在响应头中添加一个名为 "Set-Cookie" 的 HTTP 响应头来完成。"Set-Cookie" 头部包含一个类似于下面的信息:

Set-Cookie: session-id=12345; Path=/; HttpOnly

其中 "session-id" 是服务器指定的 cookie 名称,"12345" 是该 session 的唯一标识符,"Path=/" 表示该 cookie 在整个网站中都可用,"HttpOnly" 表示该 cookie 仅能通过 HTTP 协议传输,而不能被 JavaScript 访问。

当客户端接收到这个 cookie 时,会将其存储在本地,并在之后的请求中自动将该 cookie 发送回服务器,以便服务器能够识别客户端的 session。


怎么在 Java Web 服务端打印所有客户端的 session?

// 获取当前 Web 应用程序中的所有 session
Enumeration<String> sessionIds = request.getSession().getServletContext().getSessionIds();

// 遍历所有 session,并打印它们的 ID 和创建时间
while (sessionIds.hasMoreElements()) {
    String sessionId = sessionIds.nextElement();
    HttpSession session = request.getSession().getServletContext().getSession(sessionId);
    System.out.println("Session ID: " + sessionId);
    System.out.println("Created Time: " + new Date(session.getCreationTime()));
}

这段代码首先获取当前 Web 应用程序中所有 session 的 ID,然后遍历所有 session 并打印它们的 ID 和创建时间。

注意:需要在 Servlet 中使用此代码,并在接收到客户端请求时调用它。


这一切到底是怎么实现的?

以 Spring Boot 自带的 Java HTTP Server 实现 tomcat 为例:tomcat-embed-core-9.0.38-sources.jar

org.apache.catalina.util.SessionConfig 中声明了 session-id 设置到 cookie 里的 name:

public class SessionConfig {
    private static final String DEFAULT_SESSION_COOKIE_NAME = "JSESSIONID";
    private static final String DEFAULT_SESSION_PARAMETER_NAME = "jsessionid";

……

org.apache.catalina.core.ApplicationSessionCookieConfig

    /**
     * Creates a new session cookie for the given session ID
     *
     * @param context     The Context for the web application
     * @param sessionId   The ID of the session for which the cookie will be
     *                    created
     * @param secure      Should session cookie be configured as secure
     * @return the cookie for the session
     */
    public static Cookie createSessionCookie(Context context,
            String sessionId, boolean secure) {

        SessionCookieConfig scc =
            context.getServletContext().getSessionCookieConfig();

        // NOTE: The priority order for session cookie configuration is:
        //       1. Context level configuration
        //       2. Values from SessionCookieConfig
        //       3. Defaults

        Cookie cookie = new Cookie(
                SessionConfig.getSessionCookieName(context), sessionId);

        // Just apply the defaults.
        cookie.setMaxAge(scc.getMaxAge());
        cookie.setComment(scc.getComment());

        if (context.getSessionCookieDomain() == null) {
            // Avoid possible NPE
            if (scc.getDomain() != null) {
                cookie.setDomain(scc.getDomain());
            }
        } else {
            cookie.setDomain(context.getSessionCookieDomain());
        }

        // Always set secure if the request is secure
        if (scc.isSecure() || secure) {
            cookie.setSecure(true);
        }

        // Always set httpOnly if the context is configured for that
        if (scc.isHttpOnly() || context.getUseHttpOnly()) {
            cookie.setHttpOnly(true);
        }

        cookie.setPath(SessionConfig.getSessionCookiePath(context));

        return cookie;
    }

org.apache.catalina.connector.Request

public class Request implements HttpServletRequest {
    protected Session doGetSession(boolean create) {
        ……
        // Creating a new session cookie based on that session
        if (session != null && trackModesIncludesCookie) {
            Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie(
                    context, session.getIdInternal(), isSecure());

            response.addSessionCookieInternal(cookie);
        }
        ……
    }
    ……
    /**
     * @return the session associated with this Request, creating one
     * if necessary.
     */
    @Override
    public HttpSession getSession() {
        Session session = doGetSession(true);
        if (session == null) {
            return null;
        }

        return session.getSession();
    }
    ……
}