下面我给你一份**《JavaWeb 程序设计:使用 JSP 实现购物车功能的完整全过程讲解》,从原理 → 设计 → 核心代码 → 运行流程**一步一步来,适合课程设计 / 实训 / 考试 / 自学使用。


一、购物车功能整体思路

在 JavaWeb(JSP + Servlet)中,实现购物车通常遵循以下思路:

核心思想

购物车数据存放在 Session 中

原因:

  • Session 属于某个用户
  • 浏览器关闭前都有效
  • 不依赖数据库,简单易实现

购物车包含的基本功能

  1. 商品列表展示
  2. 添加商品到购物车
  3. 查看购物车
  4. 修改商品数量
  5. 删除商品
  6. 计算总价

二、项目结构设计(经典 JavaWeb)

ShoppingCart/
│
├── src/
│   ├── entity/
│   │   └── Product.java
│   ├── servlet/
│   │   └── CartServlet.java
│
├── WebContent/
│   ├── product.jsp
│   ├── cart.jsp
│   └── index.jsp
│
└── web.xml


三、实体类设计(Product)

购物车中存储的是 商品对象 + 数量

package entity;

public class Product {
    private int id;
    private String name;
    private double price;
    private int quantity;

    public Product(int id, String name, double price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    // getter / setter 省略
}


四、商品展示页面(product.jsp)

用于显示商品列表并提供「加入购物车」按钮。

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>商品列表</title>
</head>
<body>
<h2>商品列表</h2>

<table border="1">
    <tr>
        <th>编号</th>
        <th>名称</th>
        <th>价格</th>
        <th>操作</th>
    </tr>

    <tr>
        <td>1</td>
        <td>Java 编程思想</td>
        <td>88</td>
        <td>
            <a href="CartServlet?action=add&id=1&name=Java编程思想&price=88">
                加入购物车
            </a>
        </td>
    </tr>

    <tr>
        <td>2</td>
        <td>Spring 实战</td>
        <td>99</td>
        <td>
            <a href="CartServlet?action=add&id=2&name=Spring实战&price=99">
                加入购物车
            </a>
        </td>
    </tr>
</table>

<a href="cart.jsp">查看购物车</a>
</body>
</html>


五、核心控制器(CartServlet)

Servlet 是购物车的“大脑”

1️⃣ 处理逻辑说明

action功能
add添加商品
remove删除商品
clear清空购物车

2️⃣ CartServlet 代码

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        Map<Integer, Product> cart =
                (Map<Integer, Product>) session.getAttribute("cart");

        if (cart == null) {
            cart = new HashMap<>();
        }

        String action = request.getParameter("action");

        if ("add".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            double price = Double.parseDouble(request.getParameter("price"));

            if (cart.containsKey(id)) {
                Product p = cart.get(id);
                p.setQuantity(p.getQuantity() + 1);
            } else {
                cart.put(id, new Product(id, name, price, 1));
            }
        }

        if ("remove".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            cart.remove(id);
        }

        if ("clear".equals(action)) {
            cart.clear();
        }

        session.setAttribute("cart", cart);
        response.sendRedirect("cart.jsp");
    }
}


六、购物车页面(cart.jsp)

展示购物车内容、总价、删除操作。

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="java.util.*, entity.Product" %>

<html>
<head>
    <title>购物车</title>
</head>
<body>
<h2>购物车</h2>

<table border="1">
    <tr>
        <th>商品名</th>
        <th>单价</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>
    </tr>

<%
    Map<Integer, Product> cart =
        (Map<Integer, Product>) session.getAttribute("cart");

    double total = 0;

    if (cart != null) {
        for (Product p : cart.values()) {
            double subtotal = p.getPrice() * p.getQuantity();
            total += subtotal;
%>
    <tr>
        <td><%=p.getName()%></td>
        <td><%=p.getPrice()%></td>
        <td><%=p.getQuantity()%></td>
        <td><%=subtotal%></td>
        <td>
            <a href="CartServlet?action=remove&id=<%=p.getId()%>">删除</a>
        </td>
    </tr>
<%
        }
    }
%>
</table>

<h3>总价:<%=total%></h3>

<a href="CartServlet?action=clear">清空购物车</a>
<br>
<a href="product.jsp">继续购物</a>
</body>
</html>


七、运行流程总结(考试必背)

  1. 用户访问商品页面
  2. 点击「加入购物车」
  3. 请求发送到 Servlet
  4. Servlet 从 Session 取购物车
  5. 添加/修改商品
  6. 返回购物车页面
  7. JSP 展示 Session 中的数据

八、常见面试 / 实训问题

Q1:为什么使用 Session?

✔ 因为 Session 能区分不同用户的购物数据

Q2:购物车数据什么时候销毁?

✔ Session 失效(浏览器关闭 / 超时)

Q3:真实项目中会这样做吗?

✔ 小项目 / 教学
✘ 实际项目会存数据库 + Redis


九、可扩展功能(加分项)

  • 使用 JSTL + EL 替代 Scriptlet
  • 数量加减按钮
  • 登录后合并购物车
  • 使用 Ajax 无刷新更新
  • 数据库存储购物车