前言
这是一份详尽、实用且权威的 java session 全面指南,涵盖了从基础概念到在 spring boot 中的应用,并包含可直接运行的代码示例。
1. 理解会话(session)
1.1 为什么需要会话?
http 协议本身是无状态的。这意味着服务器在处理完一个客户端请求后,就会“忘记”这个客户端。当下一个请求到来时,服务器无法直接知道这个新请求是否来自之前同一个用户。
例如:
- 用户 a 登录了购物网站,添加了商品到购物车。
- 用户 a 点击结算时,服务器需要知道这个请求来自 已经登录的 用户 a,并且需要知道用户 a 的购物车里有哪些商品。
如果 http 是无状态的,服务器就无法将这些操作关联到同一个用户 a 身上。这就需要一种机制在多个请求之间保持用户的状态信息。这就是 session(会话) 要解决的问题。
1.2 会话的本质是什么?
会话(session) 是服务器端用来跟踪特定用户(或浏览器实例)的一种机制。服务器为每个用户(或浏览器会话)创建一个唯一的、服务器端存储的会话对象。这个对象就像一个临时的、用户专属的存储空间。
关键点:
- 服务器端存储: 会话数据存储在服务器内存、数据库或缓存中。客户端通常只保存一个用于标识会话的 id。
- 唯一标识: 每个会话有一个唯一的 id (session id)。
- 用户关联: 服务器通过 session id 将后续的请求与之前创建的会话关联起来。
- 临时性: 会话通常只在用户与网站交互期间有效,一段时间不活动后会被销毁。
1.3 会话与 cookie 的关系与区别
会话的实现通常依赖于 cookie 或 url 重写 来传递 session id。
最常见方式 (cookie):
- 用户第一次访问服务器(无 session id)。
- 服务器创建一个新的
httpsession对象,生成唯一的 session id。 - 服务器在 http 响应中发送一个名为
jsessionid(或其他名称) 的 cookie,其值就是这个 session id。 - 用户的浏览器保存这个 cookie。
- 用户在后续的请求中,浏览器会自动将这个
jsessionidcookie 包含在 http 请求头中发送给服务器。 - 服务器收到请求,读取
jsessionid的值,找到对应的httpsession对象,从而获取或存储该用户的会话数据。
关系:
- cookie 是传递 session id 的一种载体。session id 是钥匙,cookie 是装钥匙的信封。
- 会话数据本身不存储在 cookie 中(安全考虑和大小限制),只存储在服务器端。
区别:
- 存储位置: session 数据在服务器,cookie 数据在客户端浏览器。
- 安全性: session 相对更安全(敏感数据不直接暴露给客户端),cookie 可能被窃取或篡改(需注意设置
httponly,secure等属性)。 - 大小限制: session 理论上可以存储更多数据(受服务器资源限制),cookie 有大小和数量限制(通常每个域名 4kb 左右)。
- 生命周期: session 生命周期由服务器配置(超时时间)或程序控制(显式销毁)。cookie 的生命周期可由服务器设置(有效期)。
1.4 会话的生命周期
- 创建: 通常发生在用户首次与服务器交互,且程序调用
request.getsession()或request.getsession(true)时。如果请求中带有有效的 session id,则获取现有会话,不会创建新会话。 - 活动: 用户持续与服务器交互,session id 通过 cookie 或 url 在每个请求中传递。服务器在此期间可以向会话中添加、读取、修改或移除属性。
- 销毁:
- 超时销毁 (inactive timeout): 最常见的销毁方式。服务器配置一个超时时间(例如 30 分钟)。如果用户在最后一次请求后,超过这个时间没有新的请求,服务器会自动销毁该会话,释放资源。
- 显式销毁: 程序调用
session.invalidate()方法主动销毁会话。通常在用户“注销”时调用。 - 应用关闭/崩溃: 如果会话存储在服务器内存中,应用重启或崩溃会导致所有内存中的会话丢失。如果使用持久化存储(如数据库、redis),会话可以存活得更久。
- 浏览器关闭: 如果用于传递 session id 的 cookie 是会话 cookie(没有设置
max-age或expires),那么关闭浏览器会删除这个 cookie,导致服务器端的会话虽然还存在(直到超时),但用户再次访问时无法通过原来的 session id 找到它(服务器会创建一个新会话)。如果 cookie 设置了有效期,关闭浏览器再打开,cookie 仍然存在,可以找到原来的会话。
2. java web 中的会话管理:httpsession
java servlet api 提供了 javax.servlet.http.httpsession 接口来实现会话管理。
2.1httpsession接口详解
httpsession 接口定义了操作会话的核心方法:
string getid(): 获取此会话的唯一标识符 (session id)。long getcreationtime(): 获取会话创建的时间,单位为自 1970 年 1 月 1 日午夜 (gmt) 以来的毫秒数。long getlastaccessedtime(): 获取客户端最后一次发送与此会话相关的请求的时间。void setmaxinactiveinterval(int interval): 设置客户端请求之间会话保持打开的最大时间间隔(以秒为单位)。负数表示会话永不过期(不推荐)。int getmaxinactiveinterval(): 获取会话的最大不活动时间(秒)。servletcontext getservletcontext(): 获取会话所属的servletcontext。object getattribute(string name): 返回绑定到此会话的指定名称的对象;如果没有该名称的对象,则返回null。void setattribute(string name, object value): 将对象绑定到此会话,使用指定的名称。如果同名属性已存在,则替换它。value可以是任何可序列化的 java 对象。void removeattribute(string name): 从此会话中移除绑定到指定名称的对象。enumeration<string> getattributenames(): 返回一个string对象的enumeration,其中包含绑定到此会话的所有属性的名称。void invalidate(): 使此会话无效并解除绑定到它的任何数据。
2.2 创建和获取httpsession
在 servlet 的 doget, dopost 等方法中,通过 httpservletrequest 对象获取会话:
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
public class myservlet extends httpservlet {
protected void doget(httpservletrequest request, httpservletresponse response) {
// 获取当前请求的会话。如果不存在,则创建一个新的会话。
httpsession session = request.getsession(); // 等同于 request.getsession(true)
// 如果只是想获取现有会话,而不想创建新会话(例如检查用户是否已登录)
httpsession existingsession = request.getsession(false);
if (existingsession != null) {
// 存在现有会话
} else {
// 不存在现有会话
}
}
}
request.getsession()或request.getsession(true): 如果请求没有有效的 session id,则创建一个新的httpsession对象并返回它。如果请求包含有效的 session id,则返回与该 id 关联的现有会话。request.getsession(false): 如果请求包含有效的 session id,则返回与该 id 关联的现有httpsession对象。否则,返回null。不会创建新会话。
2.3 在会话中存储数据
使用 setattribute(string name, object value) 方法将数据存储在会话中。value 应该是可序列化的对象(如果考虑集群或持久化存储)。
session.setattribute("username", "张三"); // 存储字符串
session.setattribute("cart", myshoppingcart); // 存储自定义对象 (myshoppingcart 应实现 serializable)
session.setattribute("logintime", new date()); // 存储 date 对象
2.4 从会话中获取数据
使用 getattribute(string name) 方法从会话中检索数据。需要强制转换为正确的类型。
string username = (string) session.getattribute("username");
shoppingcart cart = (shoppingcart) session.getattribute("cart");
date logintime = (date) session.getattribute("logintime");
2.5 使会话失效
通常在用户注销时调用 invalidate() 方法。这会立即销毁会话对象,并移除其中存储的所有属性。服务器通常会发送一个过期时间为 0 的 jsessionid cookie,指示浏览器删除它。
protected void dopost(httpservletrequest request, httpservletresponse response) {
// 处理注销逻辑...
httpsession session = request.getsession(false);
if (session != null) {
session.invalidate(); // 销毁会话
}
// 重定向到登录页或首页...
}
2.6 监听会话事件:httpsessionlistener
实现 httpsessionlistener 接口可以监听会话的创建和销毁事件。
import javax.servlet.http.httpsessionevent;
import javax.servlet.http.httpsessionlistener;
public class mysessionlistener implements httpsessionlistener {
@override
public void sessioncreated(httpsessionevent se) {
// 当一个新的 httpsession 被创建时调用
system.out.println("session created: " + se.getsession().getid());
}
@override
public void sessiondestroyed(httpsessionevent se) {
// 当一个 httpsession 即将被销毁(超时或 invalidate)时调用
system.out.println("session destroyed: " + se.getsession().getid());
}
}
需要在 web.xml 中注册监听器:
<listener>
<listener-class>com.yourpackage.mysessionlistener</listener-class>
</listener>或者在支持注解的 servlet 容器中(如 tomcat 7+),使用 @weblistener:
@weblistener
public class mysessionlistener implements httpsessionlistener {
// ... 实现方法 ...
}
2.7 监听会话属性 事件:httpsessionattributelistener
实现 httpsessionattributelistener 接口可以监听会话中属性的添加、移除和替换事件。
import javax.servlet.http.httpsessionattributelistener;
import javax.servlet.http.httpsessionbindingevent;
public class mysessionattributelistener implements httpsessionattributelistener {
@override
public void attributeadded(httpsessionbindingevent event) {
// 当有属性被添加到会话中时调用
system.out.println("attribute added: " + event.getname() + " = " + event.getvalue());
}
@override
public void attributeremoved(httpsessionbindingevent event) {
// 当有属性从会话中被移除时调用
system.out.println("attribute removed: " + event.getname());
}
@override
public void attributereplaced(httpsessionbindingevent event) {
// 当会话中已有的属性被新值替换时调用
system.out.println("attribute replaced: " + event.getname() + " (old value: " + event.getvalue() + ")");
// 注意:event.getvalue() 返回的是被替换的旧值!
}
}
注册方式与 httpsessionlistener 相同(web.xml 或 @weblistener)。
2.8 会话超时配置
会话超时时间可以通过多种方式配置:
在
web.xml中配置 (适用于整个应用):<session-config> <session-timeout>30</session-timeout> <!-- 单位:分钟 --> </session-config>在程序中动态设置 (针对特定会话):
session.setmaxinactiveinterval(60 * 30); // 设置超时时间为 30 分钟 (1800 秒)
在 servlet 容器 (如 tomcat) 的全局配置文件中设置 (如
conf/web.xml): 这会作为所有应用的默认值。
3. spring boot 中的会话管理
spring boot 简化了 java web 开发,包括会话管理。它自动配置了底层的 servlet 容器(如 tomcat, jetty),并提供了便捷的注解来使用会话。
3.1 spring boot 对会话的自动化配置
- spring boot 启动 web 应用时,会自动配置
httpsession所需的环境。 - 默认情况下,会话存储在 servlet 容器的内存中。
- spring boot 提供了
server.servlet.session.*配置属性来定制会话行为(如超时时间、cookie 设置)。
3.2 在 controller 中使用httpsession
在 spring mvc 的 @controller 或 @restcontroller 中,可以直接将 httpsession 作为方法参数注入:
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.getmapping;
import javax.servlet.http.httpsession;
@controller
public class mycontroller {
@getmapping("/storeinsession")
public string storedata(httpsession session) {
session.setattribute("key", "value stored in spring boot session");
return "redirect:/result";
}
@getmapping("/getfromsession")
public string getdata(httpsession session) {
string value = (string) session.getattribute("key");
// ... 使用 value ...
return "resultpage";
}
}
3.3 使用@sessionattributes注解
@sessionattributes 注解用于在 controller 级别 声明模型属性(model attributes)应该存储在会话中。这些属性会在多个请求之间保持(跨越同一个 controller 的多个方法)。
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.sessionattributes;
import org.springframework.web.bind.support.sessionstatus;
@controller
@requestmapping("/multistepform")
@sessionattributes({"step1data", "step2data"}) // 指定哪些模型属性名要存入会话
public class multistepformcontroller {
@modelattribute("step1data") // 初始化模型属性 (可选)
public step1data initstep1data() {
return new step1data();
}
@getmapping("/step1")
public string showstep1form(@modelattribute("step1data") step1data step1data) {
return "step1form";
}
@postmapping("/step1")
public string processstep1(@modelattribute("step1data") step1data step1data) {
// 处理 step1 数据。因为 step1data 在 @sessionattributes 中,它会自动保存到会话
return "redirect:/multistepform/step2";
}
@getmapping("/step2")
public string showstep2form(@modelattribute("step2data") step2data step2data) {
return "step2form";
}
@postmapping("/step2")
public string processstep2(@modelattribute("step2data") step2data step2data,
@modelattribute("step1data") step1data step1data, // 从会话获取 step1data
sessionstatus sessionstatus) {
// 处理 step2 数据,并结合 step1data 完成整个表单
// ...
// 清除会话中由 @sessionattributes 存储的属性 (可选)
sessionstatus.setcomplete(); // 清除 step1data, step2data
return "confirmationpage";
}
}
注意:
@sessionattributes指定的属性存储在会话中,但仅限于当前 controller 内部的方法调用。- 使用
sessionstatus.setcomplete()可以清除这些会话属性。 - 它不同于直接使用
httpsession的setattribute/getattribute。
3.4 使用@sessionattribute注解
@sessionattribute 注解用于在方法参数上,指示参数值应该从会话中获取,而不是从请求参数或模型中获取。
@getmapping("/viewcart")
public string viewcart(@sessionattribute("shoppingcart") shoppingcart cart, model model) {
model.addattribute("cartitems", cart.getitems());
return "cartview";
}
这个注解通常用于访问那些不是通过 @sessionattributes 声明,而是由你直接通过 session.setattribute 或其他方式存储在会话中的属性。
3.5 在服务层或工具类中获取httpsession
有时需要在非 controller 的组件(如 service, util)中访问会话。可以通过 httpservletrequest 来间接获取 httpsession。
import org.springframework.stereotype.service;
import org.springframework.web.context.request.requestcontextholder;
import org.springframework.web.context.request.servletrequestattributes;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpsession;
@service
public class myservice {
public void dosomethingwithsession() {
// 获取当前请求的 httpservletrequest
servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.currentrequestattributes();
httpservletrequest request = attributes.getrequest();
// 获取 httpsession (谨慎使用,确保当前线程在处理 web 请求)
httpsession session = request.getsession(false);
if (session != null) {
object value = session.getattribute("key");
// ... 使用 value ...
}
}
}
重要提示: 这种方式依赖于 requestcontextholder,它使用 threadlocal 来存储当前请求的属性。只有在处理 web 请求的线程中调用这个方法才有效(例如,在 controller 调用的 service 方法中)。在异步任务、定时任务或其他非请求线程中调用会失败(requestcontextholder 获取不到请求)。
3.6 spring boot 中的会话超时配置
在 spring boot 的配置文件(application.properties 或 application.yml)中设置:
# application.properties server.servlet.session.timeout=30m # 设置会话超时为 30 分钟。单位: s(秒), m(分钟), h(小时), d(天)
# application.yml
server:
servlet:
session:
timeout: 30m
这个配置最终会调用 session.setmaxinactiveinterval()。它覆盖了 web.xml 中的设置。
4. 最佳实践与注意事项
4.1 存储什么类型的数据?
- 推荐存储:
- 用户标识符(如用户 id、用户名)
- 轻量级的用户状态信息(如登录状态、角色标识)
- 临时性、非关键性数据(如购物车信息、多步骤表单的中间数据)
- 避免存储:
- 大量数据: 影响服务器性能(内存、序列化/反序列化开销)。考虑使用数据库或缓存。
- 敏感数据: 如密码、信用卡号。即使存储在服务器端,也要确保会话存储本身的安全(加密、安全传输 session id)。
- 频繁变化的业务数据: 更适合存储在数据库或缓存中。
- 不可序列化的对象: 如果应用需要支持集群或持久化会话存储,存储在会话中的对象必须实现
java.io.serializable接口。
4.2 会话大小与性能考虑
- 保持会话精简: 只存储必要的最小数据。移除不再需要的属性 (
removeattribute)。 - 监控会话大小: 大型应用应监控会话数量和平均大小,防止内存溢出(oom)。可以使用监听器记录会话创建时的属性信息(注意性能)。
- 超时时间合理: 设置合适的超时时间,平衡用户体验(避免频繁重新登录)和服务器资源消耗(及时释放闲置会话)。
- 考虑替代方案: 对于非常大的数据(如复杂的购物车),考虑存储在数据库或分布式缓存中,会话中只保存一个引用 id。
4.3 安全性考虑
- session fixation 攻击防护: 用户登录成功后,调用
session.invalidate()销毁旧会话,再创建一个新会话 (request.getsession(true)),并赋予新的 session id。这可以防止攻击者预先获取一个有效 session id 并诱导用户使用它登录。// 登录成功后 httpsession oldsession = request.getsession(false); if (oldsession != null) { oldsession.invalidate(); } httpsession newsession = request.getsession(true); // 创建新会话 newsession.setattribute("user", authenticateduser); - 安全传输 session id:
- 确保
jsessionidcookie 设置了secure属性(仅通过 https 传输)。在 spring boot 中可通过server.servlet.session.cookie.secure=true配置。 - 设置
httponly属性(防止 javascript 访问 cookie 以减少 xss 攻击风险)。spring boot 默认启用httponly。
- 确保
- 验证会话数据: 从会话中获取数据时,不要完全信任其内容,特别是涉及权限或流程控制的数据。例如,检查用户 id 是否与当前操作匹配。
- 避免在 url 中暴露 session id (url 重写): 除非必要且已考虑安全风险,否则优先使用 cookie 传输 session id。如果必须使用 url 重写(如浏览器禁用 cookie),需格外注意安全。
4.4 分布式环境下的会话管理 (简介)
当应用部署在多台服务器(集群)时,用户的不同请求可能被负载均衡器分发到不同的服务器实例。如果会话存储在单个服务器的内存中,用户后续请求如果落到另一台服务器,将无法找到之前的会话(导致用户需要重新登录)。
解决方案:
- 粘性会话 (sticky session / session affinity): 配置负载均衡器,将同一用户的请求始终路由到同一台服务器。缺点:缺乏真正的容错性(该服务器宕机则会话丢失),负载可能不均。
- 共享会话存储: 将会话数据存储在外部所有服务器都能访问的地方。
- 数据库持久化: 将会话数据序列化后存储到数据库(如 mysql)。性能相对较低。
- 分布式缓存/内存存储: 使用如 redis, memcached, hazelcast 等高性能分布式缓存存储会话数据。这是目前最流行的方案。
- spring session 项目: 为 spring 应用提供了透明的、支持多种存储(redis, jdbc, hazelcast 等)的分布式会话解决方案。它抽象了底层的
httpsession实现,使得代码使用httpsession的方式几乎不变。我们将在案例三中演示。
4.5 替代方案 (token, jwt 等)
对于 restful api 或前后端分离架构,基于 cookie/session 的状态管理可能不再适用。常用替代方案包括:
- token-based authentication (基于令牌的认证): 服务器在用户登录成功后生成一个令牌(token)返回给客户端(通常在响应体中)。客户端在后续请求的
authorization头(如bearer <token>)中携带此令牌。服务器验证令牌有效性。令牌本身可以包含用户信息(如 jwt)或只是一个随机标识符(服务器需存储令牌与用户的映射关系)。 - jwt (json web token): 一种开放标准 (rfc 7519),用于安全地在各方之间传输信息作为 json 对象。jwt 通常包含用户标识、有效时间等信息,并经过签名或加密。服务器验证签名即可信任其内容,无需在服务器端存储会话状态(无状态)。非常适合 restful api。注意 jwt 本身无法撤销(除非有效期很短或使用黑名单机制)。
5. 实战案例:可直接运行的 spring boot 应用
以下案例假设您已创建一个基本的 spring boot web 项目 (使用 spring initializr, 选择 web -> spring web 依赖)。
5.1 案例一:用户登录状态管理
5.1.1 场景描述
实现一个简单的用户登录功能。用户输入用户名密码(模拟验证),登录成功后记录用户信息到 session。后续访问需要登录才能查看的页面时,检查 session 中是否存在用户信息。提供注销功能销毁 session。
5.1.2 核心代码实现
user类 (简化版):package com.example.sessiondemo.model; import java.io.serializable; public class user implements serializable { // 实现 serializable 以备分布式存储 private string username; // 省略构造函数、getter、setter }logincontroller:package com.example.sessiondemo.controller; import com.example.sessiondemo.model.user; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestparam; import javax.servlet.http.httpsession; @controller public class logincontroller { // 模拟用户验证 private boolean isvaliduser(string username, string password) { // 实际应用中应查询数据库 return "admin".equals(username) && "123456".equals(password); } @getmapping("/login") public string loginpage() { return "login"; // 返回 login.html 视图 } @postmapping("/login") public string login(@requestparam string username, @requestparam string password, httpsession session, model model) { if (isvaliduser(username, password)) { // 登录成功,创建 user 对象存入 session user user = new user(); user.setusername(username); session.setattribute("user", user); return "redirect:/dashboard"; // 重定向到仪表盘 } else { model.addattribute("error", "invalid username or password"); return "login"; // 返回登录页并显示错误 } } @getmapping("/dashboard") public string dashboard(httpsession session, model model) { user user = (user) session.getattribute("user"); if (user == null) { // 用户未登录,重定向到登录页 return "redirect:/login"; } model.addattribute("username", user.getusername()); return "dashboard"; // 返回 dashboard.html 视图 } @getmapping("/logout") public string logout(httpsession session) { // 使会话失效 session.invalidate(); return "redirect:/login"; } }视图模板 (thymeleaf 示例):
src/main/resources/templates/login.html<!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>login</title> </head> <body> <h1>login</h1> <div th:if="${error}" th:text="${error}" style="color: red;"></div> <form th:action="@{/login}" method="post"> username: <input type="text" name="username"> password: <input type="password" name="password"> <button type="submit">login</button> </form> </body> </html>src/main/resources/templates/dashboard.html<!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>dashboard</title> </head> <body> <h1>welcome, <span th:text="${username}">user</span>!</h1> <p>this is your dashboard.</p> <a th:href="@{/logout}" rel="external nofollow" >logout</a> </body> </html>
5.1.3 完整可运行代码结构
src/
main/
java/
com.example.sessiondemo/
sessiondemoapplication.java // spring boot 主类
controller/
logincontroller.java
model/
user.java
resources/
application.properties
templates/
login.html
dashboard.html
5.2 案例二:购物车功能实现
5.2.1 场景描述
实现一个简单的购物车。用户可以将商品加入购物车,查看购物车内容。购物车信息存储在用户的 session 中。
5.2.2 核心代码实现
product类:package com.example.sessiondemo.model; import java.io.serializable; public class product implements serializable { private long id; private string name; private double price; // 省略构造函数、getter、setter }cartitem类 (购物车项):package com.example.sessiondemo.model; import java.io.serializable; public class cartitem implements serializable { private product product; private int quantity; // 省略构造函数、getter、setter public double gettotalprice() { return product.getprice() * quantity; } }shoppingcart类 (购物车):package com.example.sessiondemo.model; import java.io.serializable; import java.util.arraylist; import java.util.list; public class shoppingcart implements serializable { private list<cartitem> items = new arraylist<>(); public void additem(product product, int quantity) { for (cartitem item : items) { if (item.getproduct().getid().equals(product.getid())) { item.setquantity(item.getquantity() + quantity); return; } } items.add(new cartitem(product, quantity)); } public list<cartitem> getitems() { return items; } public double gettotalamount() { return items.stream().maptodouble(cartitem::gettotalprice).sum(); } public void clear() { items.clear(); } }productcontroller(模拟商品列表):package com.example.sessiondemo.controller; import com.example.sessiondemo.model.product; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.getmapping; import java.util.arrays; import java.util.list; @controller public class productcontroller { @getmapping("/products") public string listproducts(model model) { // 模拟商品数据 list<product> products = arrays.aslist( new product(1l, "product a", 10.0), new product(2l, "product b", 20.0), new product(3l, "product c", 30.0) ); model.addattribute("products", products); return "productlist"; } }cartcontroller:package com.example.sessiondemo.controller; import com.example.sessiondemo.model.cartitem; import com.example.sessiondemo.model.product; import com.example.sessiondemo.model.shoppingcart; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.postmapping; import org.springframework.web.bind.annotation.requestparam; import javax.servlet.http.httpsession; @controller public class cartcontroller { @postmapping("/cart/add") public string addtocart(@requestparam long productid, @requestparam int quantity, httpsession session) { // 实际应用中应根据 productid 从数据库获取 product product product = new product(productid, "product " + productid, productid * 10.0); // 模拟 // 获取或创建购物车 shoppingcart cart = (shoppingcart) session.getattribute("cart"); if (cart == null) { cart = new shoppingcart(); session.setattribute("cart", cart); } cart.additem(product, quantity); return "redirect:/cart"; // 重定向到购物车页面 } @getmapping("/cart") public string viewcart(httpsession session, model model) { shoppingcart cart = (shoppingcart) session.getattribute("cart"); model.addattribute("cart", cart); return "cartview"; } @postmapping("/cart/clear") public string clearcart(httpsession session) { shoppingcart cart = (shoppingcart) session.getattribute("cart"); if (cart != null) { cart.clear(); } return "redirect:/cart"; } }视图模板:
src/main/resources/templates/productlist.html<!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>products</title> </head> <body> <h1>product list</h1> <table> <tr th:each="product : ${products}"> <td th:text="${product.name}"></td> <td th:text="${product.price}"></td> <td> <form th:action="@{/cart/add}" method="post"> <input type="hidden" name="productid" th:value="${product.id}"> <input type="number" name="quantity" value="1" min="1"> <button type="submit">add to cart</button> </form> </td> </tr> </table> <a th:href="@{/cart}" rel="external nofollow" >view cart</a> </body> </html>src/main/resources/templates/cartview.html<!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>shopping cart</title> </head> <body> <h1>your shopping cart</h1> <table th:if="${cart != null and !cart.items.empty}"> <tr> <th>product</th> <th>price</th> <th>quantity</th> <th>total</th> </tr> <tr th:each="item : ${cart.items}"> <td th:text="${item.product.name}"></td> <td th:text="${item.product.price}"></td> <td th:text="${item.quantity}"></td> <td th:text="${item.totalprice}"></td> </tr> <tr> <td colspan="3">total amount:</td> <td th:text="${cart.totalamount}"></td> </tr> </table> <p th:if="${cart == null or cart.items.empty}">your cart is empty.</p> <form th:action="@{/cart/clear}" method="post" th:if="${cart != null and !cart.items.empty}"> <button type="submit">clear cart</button> </form> <a th:href="@{/products}" rel="external nofollow" >continue shopping</a> </body> </html>
5.2.3 完整可运行代码结构
src/
main/
java/
com.example.sessiondemo/
sessiondemoapplication.java
controller/
logincontroller.java // (可选,如果和案例一结合)
productcontroller.java
cartcontroller.java
model/
user.java // (可选)
product.java
cartitem.java
shoppingcart.java
resources/
application.properties
templates/
login.html // (可选)
dashboard.html // (可选)
productlist.html
cartview.html
5.3 案例三:分布式会话管理 (使用 spring session + redis)
5.3.1 场景描述与为什么需要分布式会话
假设应用部署在两个实例 (instance a 和 instance b) 上,由负载均衡器分发请求。用户 u1 在 instance a 登录,session 存储在 a 的内存中。用户 u1 的下一个请求被负载均衡器分发到 instance b。instance b 在自己的内存中找不到 u1 的 session,导致 u1 需要重新登录。用户体验差。
解决方案: 使用 spring session 结合 redis 实现分布式会话存储。所有服务器实例都从同一个 redis 中读写会话数据。
5.3.2 依赖引入与配置
添加依赖 (
pom.xml):<!-- spring boot starter web --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <!-- spring session data redis --> <dependency> <groupid>org.springframework.session</groupid> <artifactid>spring-session-data-redis</artifactid> </dependency> <!-- spring data redis starter --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> </dependency>配置 redis 连接 (
application.properties):# redis 服务器地址 spring.redis.host=localhost # redis 服务器端口 spring.redis.port=6379 # redis 密码 (如果设置了) # spring.redis.password=yourpassword # redis 数据库索引 (默认 0) spring.redis.database=0 # 配置 spring session 存储类型为 redis spring.session.store-type=redis # (可选) 配置 session 在 redis 中的过期时间 (秒), 会覆盖 server.servlet.session.timeout # spring.session.redis.flush-mode=on_save # spring.session.redis.time-to-live=1800
主类启用 spring session (
sessiondemoapplication.java):import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.session.data.redis.config.annotation.web.http.enableredishttpsession; @springbootapplication @enableredishttpsession // 启用 spring session 并指定使用 redis 存储 httpsession public class sessiondemoapplication { public static void main(string[] args) { springapplication.run(sessiondemoapplication.class, args); } }
5.3.3 核心代码实现 (与普通 session 使用方式一致)
关键点: spring session 透明地替换了底层的 httpsession 实现。这意味着你之前使用 httpsession 的代码(如案例一、案例二中的 logincontroller、cartcontroller)几乎不需要修改! 它们仍然通过 request.getsession() 获取 session,通过 setattribute/getattribute 存取数据。spring session 负责将这些操作桥接到 redis 存储。
logincontroller、cartcontroller等代码保持案例一、案例二中的写法不变。user、shoppingcart等存储在 session 中的对象必须实现serializable接口,因为 redis 存储需要序列化。
5.3.4 完整可运行代码结构
在案例一或案例二代码结构的基础上:
- 添加上述依赖到
pom.xml。 - 添加 redis 配置到
application.properties。 - 在主类上添加
@enableredishttpsession。 - 确保所有存储在 session 中的对象 (
user,shoppingcart,cartitem,product) 都实现java.io.serializable。 - 安装并运行 redis 服务器 (localhost:6379)。
测试:
- 启动两个 spring boot 应用实例 (设置不同的端口
server.port=8081,server.port=8082在配置文件中)。 - 通过负载均衡器 (或直接访问不同端口) 测试登录、购物车功能。用户在一个实例上的操作(如登录、加购),在另一个实例访问时应能看到相同的状态。
总结
本指南详细介绍了 java session 的核心概念、httpsession api 的使用、在 spring boot 中的集成方式、最佳实践以及分布式环境下的解决方案(spring session + redis)。通过三个完整的实战案例,展示了 session 在不同场景下的应用。希望这份指南能帮助您深入理解和有效地在项目中应用 java session。
到此这篇关于java session原理、应用与实践全面指南的文章就介绍到这了,更多相关java session原理、应用与实践内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论