用session对象生成实现购物车的jsp代码
时间: 2024-05-29 18:11:25 浏览: 11
以下是使用session对象实现购物车的JSP代码示例:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 在JSP页面中使用session对象来实现购物车 --%>
<%
// 获取session对象
HttpSession session = request.getSession();
// 初始化购物车
if (session.getAttribute("cart") == null) {
session.setAttribute("cart", new HashMap<String, Integer>());
}
// 处理添加商品请求
if (request.getParameter("add") != null) {
String product = request.getParameter("product");
int quantity = Integer.parseInt(request.getParameter("quantity"));
// 获取购物车对象
Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart");
// 更新购物车
if (cart.containsKey(product)) {
cart.put(product, cart.get(product) + quantity);
} else {
cart.put(product, quantity);
}
// 更新session对象
session.setAttribute("cart", cart);
}
// 处理删除商品请求
if (request.getParameter("remove") != null) {
String product = request.getParameter("product");
// 获取购物车对象
Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart");
// 更新购物车
cart.remove(product);
// 更新session对象
session.setAttribute("cart", cart);
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物车示例</title>
</head>
<body>
<h1>购物车示例</h1>
<%-- 显示购物车内容 --%>
<ul>
<%-- 获取购物车对象 --%>
<% Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart"); %>
<% if (cart.isEmpty()) { %>
<li>购物车为空。</li>
<% } else { %>
<% for (String product : cart.keySet()) { %>
<li><%= product %> x <%= cart.get(product) %> <a href="?remove=true&product=<%= product %>">删除</a></li>
<% } %>
<% } %>
</ul>
<%-- 添加商品表单 --%>
<h2>添加商品</h2>
<form method="post">
<label for="product">商品名称:</label>
<input type="text" id="product" name="product"><br>
<label for="quantity">数量:</label>
<input type="number" id="quantity" name="quantity"><br>
<button type="submit" name="add" value="true">添加</button>
</form>
</body>
</html>
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)