需求分析
购物车模块(Session方法)
Ⅰ、购物车模型创建
在com.gychen.pojo里创建CartItem商品项对象和Cart购物车对象
1 package com.gychen.pojo; 2 3 import java.math.BigDecimal; 4 5 /** 6 * 购物车商品项 7 */ 8 public class CartItem { 9 10 private Integer id; 11 private String name; 12 private Integer count; 13 private BigDecimal price; 14 private BigDecimal totalPrice; 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public String getName() { 25 return name; 26 } 27 28 public void setName(String name) { 29 this.name = name; 30 } 31 32 public Integer getCount() { 33 return count; 34 } 35 36 public void setCount(Integer count) { 37 this.count = count; 38 } 39 40 public BigDecimal getPrice() { 41 return price; 42 } 43 44 public void setPrice(BigDecimal price) { 45 this.price = price; 46 } 47 48 public BigDecimal getTotalPrice() { 49 return totalPrice; 50 } 51 52 public void setTotalPrice(BigDecimal totalPrice) { 53 this.totalPrice = totalPrice; 54 } 55 56 57 /** 58 * 商品项信息 59 * @param id 商品id 60 * @param name 商品名称 61 * @param count 商品数量 62 * @param price 商品单价 63 * @param totalPrice 商品总价 64 */ 65 public CartItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice) { 66 this.id = id; 67 this.name = name; 68 this.count = count; 69 this.price = price; 70 this.totalPrice = totalPrice; 71 } 72 73 74 public CartItem() { 75 } 76 77 @Override 78 public String toString() { 79 return "CartItem{" + 80 "id=" + id + 81 ", name='" + name + '\'' + 82 ", count=" + count + 83 ", price=" + price + 84 ", totalPrice=" + totalPrice + 85 '}'; 86 } 87 } 88 89 CartItem.java
1 package com.gychen.pojo; 2 3 import java.math.BigDecimal; 4 import java.util.ArrayList; 5 import java.util.List; 6 7 /** 8 * 购物车对象 9 */ 10 public class Cart { 11 12 private Integer totalCount; 13 private BigDecimal totalPrice; 14 private List<CartItem> items = new ArrayList<CartItem>(); 15 16 17 public Integer getTotalCount() { 18 return totalCount; 19 } 20 21 public void setTotalCount(Integer totalCount) { 22 this.totalCount = totalCount; 23 } 24 25 public BigDecimal getTotalPrice() { 26 return totalPrice; 27 } 28 29 public void setTotalPrice(BigDecimal totalPrice) { 30 this.totalPrice = totalPrice; 31 } 32 33 public List<CartItem> getItems() { 34 return items; 35 } 36 37 public void setItems(List<CartItem> items) { 38 this.items = items; 39 } 40 41 42 public Cart(Integer totalCount, BigDecimal totalPrice, List<CartItem> items) { 43 this.totalCount = totalCount; 44 this.totalPrice = totalPrice; 45 this.items = items; 46 } 47 48 public Cart() { 49 } 50 51 52 @Override 53 public String toString() { 54 return "Cart{" + 55 "totalCount=" + totalCount + 56 ", totalPrice=" + totalPrice + 57 ", items=" + items + 58 '}'; 59 } 60 } 61 62 Cart.java
在Cart对象中添加需要的方法
1 package com.gychen.pojo; 2 3 import java.math.BigDecimal; 4 import java.util.LinkedHashMap; 5 import java.util.Map; 6 7 /** 8 * 购物车对象 9 */ 10 public class Cart { 11 12 // private Integer totalCount; 13 // private BigDecimal totalPrice; 14 /** 15 * key是商品编号 16 * value是商品信息 17 */ 18 private Map<Integer,CartItem> items = new LinkedHashMap<Integer, CartItem>(); 19 20 21 /** 22 * 添加商品项 23 * @param cartItem 商品项对象 24 */ 25 public void addItem(CartItem cartItem){ 26 27 //先查看购物车中是否已经添加过此商品 28 //1、如果已添加,则数量+1 29 //2、如果未添加,直接方到集合中即可 30 CartItem item = items.get(cartItem.getId()); 31 if (item == null){ 32 //之前没有添加过此商品 33 items.put(cartItem.getId(),cartItem); 34 }else { 35 36 //已经添加过的情况 数量+1,总价更新 37 item.setCount(item.getCount() + 1); //数量累加 38 item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount()))); //更新总金额 39 } 40 41 } 42 43 44 45 /** 46 * 删除商品项 47 * @param id 商品项id 48 */ 49 public void deleteItem(Integer id){ 50 51 items.remove(id); 52 } 53 54 55 /** 56 * 清空购物车 57 */ 58 public void clear(){ 59 60 items.clear(); 61 } 62 63 64 /** 65 * 修改商品数量 66 * @param id 商品项id 67 * @param count 商品数量 68 */ 69 public void uppdateCount(Integer id, Integer count){ 70 71 //先查看购物车是否有此商品,如果有修改数量,更新总金额 72 73 CartItem cartItem = items.get(id); 74 if (cartItem != null){ 75 cartItem.setCount(count); //修改商品数量 76 cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount()))); //更新总金额 77 } 78 } 79 80 81 82 83 84 private Integer getTotalCount() { 85 Integer totalCount = 0; 86 //法一:遍历Map集合中的每个键值对 87 for (Map.Entry<Integer,CartItem>entry : items.entrySet()){ 88 totalCount += entry.getValue().getCount(); 89 } 90 // //法二: 91 // for (CartItem value : items.values()) { 92 // totalCount += value.getCount(); 93 // } 94 return totalCount; 95 } 96 97 //实际上并不需要 98 // public void setTotalCount(Integer totalCount) { 99 // this.totalCount = totalCount; 100 // } 101 102 private BigDecimal getTotalPrice() { 103 BigDecimal totalPrice = new BigDecimal(0); 104 for (Map.Entry<Integer,CartItem>entry : items.entrySet()){ 105 totalPrice = totalPrice.add(entry.getValue().getTotalPrice()); 106 } 107 return totalPrice; 108 } 109 110 // public void setTotalPrice(BigDecimal totalPrice) { 111 // this.totalPrice = totalPrice; 112 // } 113 114 public Map<Integer,CartItem> getItems() { 115 return items; 116 } 117 118 public void setItems(Map<Integer,CartItem> items) { 119 this.items = items; 120 } 121 122 123 124 @Override 125 public String toString() { 126 return "Cart{" + 127 "totalCount=" + getTotalCount() + 128 ", totalPrice=" + getTotalPrice() + 129 ", items=" + items + 130 '}'; 131 } 132 } 133 134 Cart.java
添加CartTest测试
1 package com.gychen.test; 2 3 import com.gychen.pojo.Cart; 4 import com.gychen.pojo.CartItem; 5 import org.junit.Test; 6 7 import java.math.BigDecimal; 8 9 import static org.junit.Assert.*; 10 11 public class CartTest { 12 13 14 @Test 15 public void addItem() { 16 Cart cart = new Cart(); 17 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(200),new BigDecimal(200))); 18 cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(100),new BigDecimal(100))); 19 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(200),new BigDecimal(200))); 20 System.out.println(cart); 21 } 22 23 @Test 24 public void deleteItem() { 25 Cart cart = new Cart(); 26 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(300),new BigDecimal(300))); 27 cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(100),new BigDecimal(100))); 28 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(300),new BigDecimal(300))); 29 30 cart.deleteItem(1); 31 32 System.out.println(cart); 33 } 34 35 @Test 36 public void clear() { 37 38 Cart cart = new Cart(); 39 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(400),new BigDecimal(400))); 40 cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(200),new BigDecimal(200))); 41 cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(400),new BigDecimal(400))); 42 43 cart.clear(); 44 45 System.out.println(cart); 46 } 47 48 @Test 49 public void uppdateCount() { 50 51 Cart cart = new Cart(); 52 cart.addItem(new CartItem(1,"Spring从入门到精通",1,new BigDecimal(400),new BigDecimal(400))); 53 cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(200),new BigDecimal(200))); 54 cart.addItem(new CartItem(1,"Spring从入门到精通",1,new BigDecimal(400),new BigDecimal(400))); 55 56 cart.uppdateCount(2,4); 57 cart.uppdateCount(1,1); 58 System.out.println(cart); 59 } 60 }
Ⅱ、加入购物车功能的实现
1 //1、获取请求的参数 2 //2、调用BookService.queryBookById(id):Book得到图书的信息 3 //3、把图书信息转化为CartItem商品项 4 //4、调用Cart.addItem(cartItem);添加商品项 5 //4、重定向回列表页
在com.gychen.web中新建CartServlet的addItem方法
1 private BookService bookService = new BookServiceImpl(); 2 /** 3 * 添加购物车 4 * @param req 请求 5 * @param resp 响应 6 */ 7 protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 8 9 //1、获取请求的参数 10 //2、调用BookService.queryBookById(id):Book得到图书的信息 11 //3、把图书信息转化为CartItem商品项 12 //4、调用Cart.addItem(cartItem);添加商品项 13 //5、重定向回列表页 14 15 //1、获取请求的参数 16 int id = WebUtils.parseInt(req.getParameter("id"),0); 17 18 //2、调用BookService.queryBookById(id):Book得到图书的信息 19 20 Book book = bookService.querryBookById(id); 21 System.out.println(book); 22 23 //3、把图书信息转化为CartItem商品项 24 CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice()); 25 26 //4、调用Cart.addItem(cartItem);添加商品项 27 Cart cart = (Cart) req.getSession().getAttribute("cart"); 28 if (cart == null){ 29 30 cart = new Cart(); 31 req.getSession().setAttribute("cart",cart); 32 } 33 34 cart.addItem(cartItem); 35 36 //5、重定向回列表页 37 //获取浏览器访问时的地址再重定向回去 38 resp.sendRedirect(req.getHeader("Referer")); 39 } 40 41 addItem();
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 <%-- 3 Created by IntelliJ IDEA. 4 User: 99622 5 Date: 2020/3/30 6 Time: 20:18 7 To change this template use File | Settings | File Templates. 8 --%> 9 <%@ page 10 contentType="text/html;charset=UTF-8" 11 language="java" 12 errorPage="/error500.jsp" 13 autoFlush="true" 14 buffer="8kb" 15 %> 16 <!-- 17 errorPage表示错误后自动跳转到error500.jsp 18 --> 19 <!DOCTYPE html> 20 <html> 21 <head> 22 <meta charset="UTF-8"> 23 <title>书城首页</title> 24 25 <%-- 静态包含 base标签、css样式、jQuery文件 --%> 26 <%@ include file="/pages/common/head.jsp"%> 27 28 29 </head> 30 <body> 31 32 <div id="header"> 33 <img class="logo_img" alt="" src="static/img/logo.gif" > 34 <span class="wel_word">网上书城</span> 35 <div> 36 <%--如果用户没有登陆,显示登录和注册--%> 37 <c:if test="${empty sessionScope.user}"> 38 <a href="pages/user/login.jsp">登录</a> | 39 <a href="pages/user/regist.jsp">注册</a> 40 </c:if> 41 42 <%--如果用户已经登陆,则显示登录成功之后的用户信息--%> 43 <c:if test="${not empty sessionScope.user}"> 44 <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临书城</span> 45 <a href="pages/order/order.jsp">我的订单</a> 46 <a href="userServlet?action=logout">注销</a> 47 </c:if> 48 <a href="pages/cart/cart.jsp">购物车</a> 49 <a href="pages/manager/manager.jsp">后台管理</a> 50 </div> 51 </div> 52 53 <div id="main"> 54 <div id="book"> 55 <div class="book_cond"> 56 <form action="" method="get"> 57 价格:<input id="min" type="text" name="min" value=""> 元 - 58 <input id="max" type="text" name="max" value=""> 元 59 <input type="submit" value="查询" /> 60 </form> 61 </div> 62 <div style="text-align: center"> 63 <span>您的购物车中有3件商品</span> 64 <div> 65 您刚刚将<span style="color: red">时间简史</span>加入到了购物车中 66 </div> 67 </div> 68 <c:forEach items="${requestScope.page.items}" var="book"> 69 <div class="b_list"> 70 <div class="img_div"> 71 <img class="book_img" alt="" src="static/img/default.jpg" /> 72 </div> 73 <div class="book_info"> 74 <div class="book_name"> 75 <span class="sp1">书名:</span> 76 <span class="sp2">${book.name}</span> 77 </div> 78 <div class="book_author"> 79 <span class="sp1">作者:</span> 80 <span class="sp2">${book.author}</span> 81 </div> 82 <div class="book_price"> 83 <span class="sp1">价格:</span> 84 <span class="sp2">¥${book.price}</span> 85 </div> 86 <div class="book_sales"> 87 <span class="sp1">销量:</span> 88 <span class="sp2">${book.sales}</span> 89 </div> 90 <div class="book_amount"> 91 <span class="sp1">库存:</span> 92 <span class="sp2">${book.stock}</span> 93 </div> 94 <div class="book_add"> 95 <button bookId="${book.id}" class="addToCart">加入购物车</button> 96 </div> 97 </div> 98 </div> 99 </c:forEach> 100 101 </div> 102 103 <div id="page_nav"> 104 <%--大于1才显示首页--%> 105 <c:if test="${requestScope.page.pageNo > 1}"> 106 <a href="client/clientbookServlet?action=page">首页</a> 107 <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}"> 108 上一页 109 </a> 110 <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}"> 111 ${requestScope.page.pageNo-1} 112 </a> 113 </c:if> 114 115 <%--当前页码--%> 116 【${ requestScope.page.pageNo }】 117 118 <%--小于末页才显示末页--%> 119 <c:if test="${requestScope.page.pageNo < requestScope.page.pageTotal}"> 120 <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}"> 121 ${requestScope.page.pageNo+1} 122 </a> 123 <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}"> 124 下一页 125 </a> 126 <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageTotal}">末页</a> 127 </c:if> 128 129 130 共${ requestScope.page.pageTotal }页,${ requestScope.page.pageTotalCount }条记录 到第 131 <input value="${requestScope.page.pageNo}" name="pn" id="pn_input"/>页 132 <input id="searchPageBtn" type="button" value="确定"> 133 </div> 134 135 </div> 136 137 <%--静态包含页脚内容--%> 138 <%@include file="/pages/common/footer.jsp"%> 139 <script> 140 $(function () { 141 $("#searchPageBtn").click(function () { 142 //获取要跳转的页面页码 143 var pageNo = $("#pn_input").val(); 144 //location的href属性是地址栏的路由,执行请求转发 145 location.href="${pageScope.basePath}client/clientbookServlet?action=page&pageNo="+pageNo; 146 }); 147 148 // 给加购按钮绑定单击事件 149 $(".addToCart").click(function () { 150 var bookId = $(this).attr("bookId"); 151 152 location.href="${pageScope.basePath}cartServlet?action=addItem&id="+bookId; 153 }) 154 }); 155 </script> 156 </body> 157 </html>