You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Servlet维护并更新ArrayList?购物车会话数据丢失问题

购物车无法累积商品的问题解决

问题重现

点击Item1的添加按钮后,购物车显示Item1;返回首页点击Item2的添加按钮后,购物车仅显示Item2,之前的Item1丢失。

问题根源

你的Servlet代码中,每次处理请求时都会新建一个空的ArrayList<Product>,并立刻覆盖session中的InCart属性,导致之前存储的购物车数据被清空。

原Servlet代码的问题行:

ArrayList<Product> cart = new ArrayList<Product>(); 
session.setAttribute("InCart", cart);

修正后的Servlet代码

HttpSession session = request.getSession(); 
// 先从session获取已有的购物车,不存在则新建
ArrayList<Product> cart = (ArrayList<Product>) session.getAttribute("InCart");
if (cart == null) {
    cart = new ArrayList<Product>();
    session.setAttribute("InCart", cart);
}

Product a = new Product("Item 1", 200);
Product b = new Product("Item 2", 50);

if (request.getParameter("item1") != null) {
    cart.add(a);
    out.println(cart.toString());
} else if (request.getParameter("item2") != null) {
    cart.add(b);
    out.print(cart.toString());
}

关键修改说明

  • 优先从session中获取已有的购物车对象,而不是每次都新建
  • 仅当session中没有购物车时,才初始化新的ArrayList并放入session
  • 后续添加商品时,操作的是同一个购物车对象,数据自然会累积

内容的提问来源于stack exchange,提问作者Luke Santi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:30:52