查看“Java 服务器和客户端的 session 是怎么实现的?”的源代码
←
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" 头部包含一个类似于下面的信息:<syntaxhighlight lang="console"> Set-Cookie: session-id=12345; Path=/; HttpOnly </syntaxhighlight>其中 "session-id" 是服务器指定的 cookie 名称,"12345" 是该 session 的唯一标识符,"Path=/" 表示该 cookie 在整个网站中都可用,"HttpOnly" 表示该 cookie 仅能通过 HTTP 协议传输,而不能被 JavaScript 访问。 当客户端接收到这个 cookie 时,会将其存储在本地,并在之后的请求中自动将该 cookie 发送回服务器,以便服务器能够识别客户端的 session。 === 怎么在 Java Web 服务端打印所有客户端的 session? === <syntaxhighlight lang="java"> // 获取当前 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())); } </syntaxhighlight>这段代码首先获取当前 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:<syntaxhighlight lang="java"> public class SessionConfig { private static final String DEFAULT_SESSION_COOKIE_NAME = "JSESSIONID"; private static final String DEFAULT_SESSION_PARAMETER_NAME = "jsessionid"; …… </syntaxhighlight>org.apache.catalina.core.ApplicationSessionCookieConfig<syntaxhighlight lang="java"> /** * 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; } </syntaxhighlight>org.apache.catalina.connector.Request<syntaxhighlight lang="java"> 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(); } …… } </syntaxhighlight>
返回至
Java 服务器和客户端的 session 是怎么实现的?
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
Spring Boot 2 零基础入门
Spring Cloud
Spring Boot
设计模式之禅
VUE
Vuex
Maven
算法
技能树
Wireshark
IntelliJ IDEA
ElasticSearch
VirtualBox
软考
正则表达式
程序员精讲
软件设计师精讲
初级程序员 历年真题
C
SQL
Java
FFmpeg
Redis
Kafka
MySQL
Spring
Docker
JMeter
Apache
Linux
Windows
Git
ZooKeeper
设计模式
Python
MyBatis
软件
数学
PHP
IntelliJ IDEA
CS基础知识
网络
项目
未分类
MediaWiki
镜像
问题
健身
国债
英语
烹饪
常见术语
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息