在javaweb中用cookie和session实现一个购物车的代码

时间: 2023-05-10 12:55:29 浏览: 99
以下是一个简单的 JavaWeb 购物车代码,使用了 Cookie 和 Session: 1. 创建一个名为 ShoppingCart 的 Java 类,用于存储购物车中的商品信息: public class ShoppingCart { private Map<String, Integer> items = new HashMap<String, Integer>(); public void addItem(String itemId, int quantity) { if (items.containsKey(itemId)) { int currentQuantity = items.get(itemId); items.put(itemId, currentQuantity + quantity); } else { items.put(itemId, quantity); } } public void removeItem(String itemId) { items.remove(itemId); } public Map<String, Integer> getItems() { return items; } public int getItemCount() { int count = 0; for (int quantity : items.values()) { count += quantity; } return count; } public double getTotalPrice() { double totalPrice = 0; for (Map.Entry<String, Integer> entry : items.entrySet()) { String itemId = entry.getKey(); int quantity = entry.getValue(); double price = getItemPrice(itemId); totalPrice += price * quantity; } return totalPrice; } private double getItemPrice(String itemId) { // 根据 itemId 查询商品价格 return 0.0; } } 2. 在 Servlet 中使用 Cookie 和 Session 来实现购物车功能: public class ShoppingCartServlet extends HttpServlet { private static final String CART_COOKIE_NAME = "cart"; private static final int CART_COOKIE_MAX_AGE = 60 * 60 * 24 * 7; // 一周 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String itemId = request.getParameter("itemId"); int quantity = Integer.parseInt(request.getParameter("quantity")); // 从 Session 中获取购物车对象 HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } // 将商品添加到购物车中 cart.addItem(itemId, quantity); // 将购物车信息保存到 Cookie 中 String cartJson = toJson(cart); Cookie cartCookie = new Cookie(CART_COOKIE_NAME, cartJson); cartCookie.setMaxAge(CART_COOKIE_MAX_AGE); response.addCookie(cartCookie); // 跳转到购物车页面 response.sendRedirect("cart.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 从 Cookie 中获取购物车信息 String cartJson = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(CART_COOKIE_NAME)) { cartJson = cookie.getValue(); break; } } } // 从 Session 中获取购物车对象 HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } // 如果 Cookie 中有购物车信息,则将其合并到 Session 中的购物车对象中 if (cartJson != null) { ShoppingCart cookieCart = fromJson(cartJson); for (Map.Entry<String, Integer> entry : cookieCart.getItems().entrySet()) { String itemId = entry.getKey(); int quantity = entry.getValue(); cart.addItem(itemId, quantity); } } // 将购物车信息保存到 Cookie 中 String cartJson = toJson(cart); Cookie cartCookie = new Cookie(CART_COOKIE_NAME, cartJson); cartCookie.setMaxAge(CART_COOKIE_MAX_AGE); response.addCookie(cartCookie); // 跳转到购物车页面 response.sendRedirect("cart.jsp"); } private String toJson(ShoppingCart cart) { Gson gson = new Gson(); return gson.toJson(cart); } private ShoppingCart fromJson(String json) { Gson gson = new Gson(); return gson.fromJson(json, ShoppingCart.class); } } 3. 在 JSP 页面中显示购物车信息: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>购物车</title> </head> <body> <h1>购物车</h1> <table> <thead> <tr> <th>商品编号</th> <th>商品名称</th> <th>单价</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="item" items="${cart.items}"> <tr> <td>${item.key}</td> <td>${getItemName(item.key)}</td> <td>${getItemPrice(item.key)}</td> <td>${item.value}</td> <td>${getItemPrice(item.key) * item.value}</td> <td><a href="removeItem?id=${item.key}">删除</a></td> </tr> </c:forEach> </tbody> <tfoot> <tr> <td colspan="4">总计:</td> <td>${cart.totalPrice}</td> <td></td> </tr> </tfoot> </table> </body> </html> 4. 在 Servlet 中实现删除商品的功能: public class RemoveItemServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String itemId = request.getParameter("id"); // 从 Session 中获取购物车对象 HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); if (cart != null) { cart.removeItem(itemId); } // 将购物车信息保存到 Cookie 中 String cartJson = toJson(cart); Cookie cartCookie = new Cookie(CART_COOKIE_NAME, cartJson); cartCookie.setMaxAge(CART_COOKIE_MAX_AGE); response.addCookie(cartCookie); // 跳转到购物车页面 response.sendRedirect("cart.jsp"); } private String toJson(ShoppingCart cart) { Gson gson = new Gson(); return gson.toJson(cart); } } 注意:以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。

相关推荐

最新推荐

JavaWeb后台购物车类实现代码详解

主要介绍了JavaWeb后台购物车类实现代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

JavaWeb使用Session和Cookie实现登录认证

本篇文章主要介绍了JavaWeb使用Session和Cookie实现登录认证,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

JavaWeb 中Cookie实现记住密码的功能示例

cookie是一种WEB服务器通过浏览器在访问者的硬盘上存储信息的手段。Cookie的目的就是为用户带来方便,为网站带来增值。这篇文章主要介绍了JavaWeb 中Cookie实现记住密码的功能示例,需要的朋友可以参考下

JavaWeb使用Cookie模拟实现自动登录功能(不需用户名和密码)

不需要填写用户名和密码自动登录系统,其实现思路使用cookie模拟浏览器自动登录,对cookie实现自动登录功能感兴趣的朋友一起学习吧

JavaWeb基于Session实现的用户登陆注销方法示例

为了安全起见,session常常用来保存用户的登录信息。...下面这篇文章就来给大家介绍了关于JavaWeb基于Session实现的用户登陆注销的相关资料,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧。

stc12c5a60s2 例程

stc12c5a60s2 单片机的所有功能的实例,包括SPI、AD、串口、UCOS-II操作系统的应用。

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire

【迁移学习在车牌识别中的应用优势与局限】: 讨论迁移学习在车牌识别中的应用优势和局限

![【迁移学习在车牌识别中的应用优势与局限】: 讨论迁移学习在车牌识别中的应用优势和局限](https://img-blog.csdnimg.cn/direct/916e743fde554bcaaaf13800d2f0ac25.png) # 1. 介绍迁移学习在车牌识别中的背景 在当今人工智能技术迅速发展的时代,迁移学习作为一种强大的技术手段,在车牌识别领域展现出了巨大的潜力和优势。通过迁移学习,我们能够将在一个领域中学习到的知识和模型迁移到另一个相关领域,从而减少对大量标注数据的需求,提高模型训练效率,加快模型收敛速度。这种方法不仅能够增强模型的泛化能力,提升识别的准确率,还能有效应对数据

margin-top: 50%;

margin-top: 50%; 是一种CSS样式代码,用于设置元素的上边距(即与上方元素或父级元素之间的距离)为其父元素高度的50%。 这意味着元素的上边距将等于其父元素高度的50%。例如,如果父元素的高度为100px,则该元素的上边距将为50px。 请注意,这个值只在父元素具有明确的高度(非auto)时才有效。如果父元素的高度是auto,则无法确定元素的上边距。 希望这个解释对你有帮助!如果你还有其他问题,请随时提问。

Android通过全局变量传递数据

在Activity之间数据传递中还有一种比较实用的方式 就是全局对象 实用J2EE的读者来说都知道Java Web的四个作用域 这四个作用域从小到大分别是Page Request Session和Application 其中Application域在应用程序的任何地方都可以使用和访问 除非是Web服务器停止 Android中的全局对象非常类似于Java Web中的Application域 除非是Android应用程序清除内存 否则全局对象将一直可以访问 1 定义一个类继承Application public class MyApp extends Application 2 在AndroidMainfest xml中加入全局变量 android:name &quot; MyApp&quot; 3 在传数据类中获取全局变量Application对象并设置数据 myApp MyApp getApplication ; myApp setName &quot;jack&quot; ; 修改之后的名称 4 在收数据类中接收Application对象 myApp MyApp getApplication ;">在Activity之间数据传递中还有一种比较实用的方式 就是全局对象 实用J2EE的读者来说都知道Java Web的四个作用域 这四个作用域从小到大分别是Page Request Session和Application 其中Application域在应用程序的任何地方都可以使用和 [更多]