1.7、修改购物车商品数量
修改 CartServlet
package com.atguigu.web; import com.atguigu.pojo.Book; import com.atguigu.pojo.Cart; import com.atguigu.pojo.CartItem; import com.atguigu.service.BookService; import com.atguigu.service.impl.BookServiceImpl; import com.atguigu.utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CartServlet extends BaseServlet{ private BookService bookService=new BookServiceImpl(); /** * 加入购物车 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // System.out.println("加入购物车"); // System.out.println("商品编号:"+req.getParameter("id")); //获取请求的参数 商品编号 int id= WebUtils.parseInt(req.getParameter("id"),0); //调用bookService.queryBookById(id):Book 得到图书的信息 Book book=bookService.queryBookById(id); //把图书信息,转换成为CartItem商品项 CartItem cartItem=new CartItem(book.getId(), book.getName(), 1,book.getPrice(),book.getPrice()); //调用Cart.addItem(CartItem):添加商品项 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart==null){ cart=new Cart(); req.getSession().setAttribute("cart",cart); } cart.addItem(cartItem); // System.out.println(cart); //重定向回商品列表页面 // resp.sendRedirect(req.getContextPath()); // System.out.println("请求头Referer的值:"+req.getHeader("Referer")); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } /** * 删除商品项 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数 商品编号 int id= WebUtils.parseInt(req.getParameter("id"),0); //获取购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //删除了购物车商品项 cart.deleteItem(id); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } /** * 清空购物车 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //清空购物车 cart.clear(); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } /** * 修改商品数量 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数 商品编号 ,商品数量 int id=WebUtils.parseInt(req.getParameter("id"),0); int count=WebUtils.parseInt(req.getParameter("count"),1); //获取Cart购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //修改商品数量 cart.updateCount(id,count); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } }
修改 cart.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/8/21 Time: 下午 02:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>购物车</title> <%--静态包含 base标签,css样式,jquery文件 --%> <%@ include file="/pages/common/head.jsp"%> <script type="text/javascript"> $(function (){ //给删除绑定单击事件 $("a.deleteItem").click(function (){ return confirm("你确定要删除吗【"+$(this).parent().parent().find("td:first").text()+"】?"); }); //给清空购物车绑定单击事件 $("#clearCart").click(function (){ return confirm("你确定要清空购物车吗?"); }); //给输入框失去焦点事件 === onchange 内容发生改变事件 $(".updateCount").change(function (){ //获取商品名称 var name=$(this).parent().parent().find("td:first").text(); //获取商品id var id=$(this).attr("bookId"); //获取商品数量 var count=this.value; if (confirm("你确定要将【"+name+"】商品修改数量为:"+count+"吗?")){ //发起请求。给服务器保存修改 location.href="http://localhost:8080/book/cartServlet?action=updateCount&count="+count+"&id="+id; }else { //defaultValue属性是表单项Dom对象的属性。它表示默认的value属性值。 this.value=this.defaultValue; } }); }); </script> </head> <body> <div id="header"> <img class="logo_img" alt="" src="static/img/logo.gif"> <span class="wel_word">购物车</span> <%-- 静态包含登录成功之后的菜单--%> <%@ include file="/pages/common/login_sucess_menu.jsp"%> </div> <div id="main"> <table> <tr> <td>商品名称</td> <td>数量</td> <td>单价</td> <td>金额</td> <td>操作</td> </tr> <c:if test="${empty sessionScope.cart.items}"> <%-- 如果购物车为空的情况 --%> <td colspan="5"><a href="index.jsp"> 亲,当前购物车为空!快跟小伙伴们去浏览商品吧!!!</a></td> </c:if> <c:if test="${not empty sessionScope.cart.items}"> <%-- 如果购物车非空的情况 --%> <c:forEach items="${sessionScope.cart.items}" var="entry"> <tr> <td>${entry.value.name}</td> <td> <input class="updateCount" style="width: 80px" bookId="${entry.value.id}" type="text" value="${entry.value.count}"> </td> <td>${entry.value.price}</td> <td>${entry.value.totalPrice}</td> <td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${entry.value.id}">删除</a></td> </tr> </c:forEach> </c:if> </table> <c:if test="${not empty sessionScope.cart.items}"> <div class="cart_info"> <span class="cart_span">购物车中共有<span class="b_count">${sessionScope.cart.totalCount}</span>件商品</span> <span class="cart_span">总金额<span class="b_price">${sessionScope.cart.totalPrice}</span>元</span> <span class="cart_span"><a id="clearCart" href="cartServlet?action=clear">清空购物车</a></span> <span class="cart span"><a href="pages/cart/checkout.jsp">去结账</a></span> </div> </c:if> </div> <%--静态包含页脚内容--%> <%@include file="/pages/common/footer.jsp"%> </body> </html>
1.8、首页,购物车回显
修改 CartServlet
package com.atguigu.web; import com.atguigu.pojo.Book; import com.atguigu.pojo.Cart; import com.atguigu.pojo.CartItem; import com.atguigu.service.BookService; import com.atguigu.service.impl.BookServiceImpl; import com.atguigu.utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CartServlet extends BaseServlet{ private BookService bookService=new BookServiceImpl(); /** * 加入购物车 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // System.out.println("加入购物车"); // System.out.println("商品编号:"+req.getParameter("id")); //获取请求的参数 商品编号 int id= WebUtils.parseInt(req.getParameter("id"),0); //调用bookService.queryBookById(id):Book 得到图书的信息 Book book=bookService.queryBookById(id); //把图书信息,转换成为CartItem商品项 CartItem cartItem=new CartItem(book.getId(), book.getName(), 1,book.getPrice(),book.getPrice()); //调用Cart.addItem(CartItem):添加商品项 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart==null){ cart=new Cart(); req.getSession().setAttribute("cart",cart); } cart.addItem(cartItem); // System.out.println(cart); //重定向回商品列表页面 // resp.sendRedirect(req.getContextPath()); // System.out.println("请求头Referer的值:"+req.getHeader("Referer")); //最后一个添加商品的名称 req.getSession().setAttribute("lastName",cartItem.getName()); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } /** * 删除商品项 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数 商品编号 int id= WebUtils.parseInt(req.getParameter("id"),0); //获取购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //删除了购物车商品项 cart.deleteItem(id); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } /** * 清空购物车 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //清空购物车 cart.clear(); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } /** * 修改商品数量 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数 商品编号 ,商品数量 int id=WebUtils.parseInt(req.getParameter("id"),0); int count=WebUtils.parseInt(req.getParameter("count"),1); //获取Cart购物车对象 Cart cart= (Cart) req.getSession().getAttribute("cart"); if (cart!=null){ //修改商品数量 cart.updateCount(id,count); //重定向回原来商品所在地址页面 resp.sendRedirect(req.getHeader("Referer")); } } }
修改 index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>书城首页</title> <%--静态包含 base标签,css样式,jquery文件 --%> <%@ include file="/pages/common/head.jsp"%> <script type="text/javascript"> $(function (){ //给加入购物车按钮绑定单击事件 $("button.addToCart").click(function (){ /** * 在事件响应的function函数中,有一个this对象,这个this对象,是当前正在响应事件的dom对象 * @type {*|jQuery} */ var bookId= $(this).attr("bookId"); location.href="http://localhost:8080/book/cartServlet?action=addItem&id="+bookId; }); }); </script> </head> <body> <div id="header"> <img class="logo_ing" alt="" src="static/img/logo.gif"> <span class= "wel_word">网上书城</span> <div> <%-- 如果用户还没有登录,显示【登录和注册的菜单】--%> <c:if test="${empty sessionScope.user}"> <a href="pages/user/login.jsp">登录</a> <a href="pages/user/regist.jsp">注册</a> </c:if> <%-- 如果已经登录,显示登录之后的用户信息--%> <c:if test="${not empty sessionScope.user}"> <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临尚硅谷书城</span> <a href="pages/order/order.jsp">我的订单</a> <a href="userServlet?action=logout">注销</a> </c:if> <a href="pages/cart/cart.jsp">购物车</a> <a href="pages/manager/manager.jsp">后台管理</a> </div> <div id="main"> <div id="book"> <div class="book_cond"> <form action="client/bookServlet" method="get"> <input type="hidden" name="action" value="pageByPrice"> 价格:<input id="min" type="text" name="min" value="${param.min}">元 - <input id="max" type="text" name="max" value="${param.max}">元 <input type="submit" value="查询"/> </form> </div> <div style="..."> <c:if test="${empty sessionScope.cart.items}"> <%-- 购物车为空的输出 --%> <span></span> <div> <span style="...">当前购物车为空</span> </div> </c:if> <c:if test="${not empty sessionScope.cart.items}"> <%-- 购物车非空的输出 --%> <span>您的购物车中有${sessionScope.cart.totalCount}件商品</span> <div> 您刚刚将<span style="...">${sessionScope.lastName}</span>加入到了购物车中 </div> </c:if> </div> <div> <c:forEach items="${requestScope.page.items}" var="book"> <div class="b_list"> <div class="img_div"> <img class="book_img" alt="${book.imgPath}"/> </div> <div class="book_info"> <div class="book_name"> <span class="sp1">书名:</span> <span class="sp2">${book.name}</span> </div> <div class="book_author"> <span class="sp1">作者:</span> <span class="sp2">${book.author}</span> </div> <div class= "book_price"> <span class="sp1">价格:</span> <span class="sp2">¥${book.price}</span> </div> <div class="book_sales"> <span class="sp1">销量:</span> <span class="sp2">${book.sales}</span> </div> <div class="book_amount"> <span class="sp1">库存:</span> <span class="sp2">${book.stock}</span> </div> <div class="book_add"> <button bookId="${book.id}" class="addToCart">加入购物车:</button> </div> </div> </div> </c:forEach> </div> </div> <%-- 静态包含分页条 --%> <%@include file="/pages/common/page_nav.jsp"%> </div> </div> <%--静态包含页脚内容--%> <%@include file="/pages/common/footer.jsp"%> </body> </html>
2、项目第七阶段:订单模块
2.1、订单模块的分析
现在只实现“生成订单”功能
2.2、订单模块的实现
2.2.1、创建订单模块的数据库表
create table t_order order_id varchar (50) primary key, create_time datetime. price decimal(11,2), status int, user id int, foreign key(user_id) references t_user (id) );
create table t_order_item( id int primary key auto_increment name varchar (100) count int, price decimal(11,2) total price decimal (11,2) order_id varchar (50) foreign key (order_id) references t_order (order_id) );
2.2.2、创建订单模块的数据模型
创建 pojo/Order
package com.atguigu.pojo; import java.math.BigDecimal; import java.util.Date; public class Order { private String orderId; private Date createTime; private BigDecimal price; //0未发货,1已发货,2已签收 private Integer status=0; private Integer userId; public Order() { } public Order(String orderId, Date createTime, BigDecimal price, Integer status, Integer userId) { this.orderId = orderId; this.createTime = createTime; this.price = price; this.status = status; this.userId = userId; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Override public String toString() { return "Order{" + "orderId='" + orderId + '\'' + ", createTime=" + createTime + ", price=" + price + ", status=" + status + ", userId=" + userId + '}'; } }
创建pojo/OrderItem
package com.atguigu.pojo; import java.math.BigDecimal; public class OrderItem { private Integer id; private String name; private Integer count; private BigDecimal price; private BigDecimal totalPrice; private String orderId; public OrderItem() { } public OrderItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice, String orderId) { this.id = id; this.name = name; this.count = count; this.price = price; this.totalPrice = totalPrice; this.orderId = orderId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } @Override public String toString() { return "OrderItem{" + "id=" + id + ", name='" + name + '\'' + ", count=" + count + ", price=" + price + ", totalPrice=" + totalPrice + ", orderId='" + orderId + '\'' + '}'; } }
2.2.3、编写订单模块的Dao程序和测试
创建dao/OrderDao
package com.atguigu.dao; import com.atguigu.pojo.Order; public interface OrderDao { public int saveOrder(Order order); }
创建 impl/OrderDaoImpl
package com.atguigu.dao.impl; import com.atguigu.dao.OrderDao; import com.atguigu.pojo.Order; public class OrderDaoImpl extends BaseDao implements OrderDao { @Override public int saveOrder(Order order) { String sql="insert into t_order(order_id,create_time,price,status,user_id)values(?,?,?,?,?)"; return update(sql,order.getOrderId(),order.getCreateTime(),order.getPrice(),order.getStatus(),order.getOrderId()); } }
创建dao/OrderItemDao
package com.atguigu.dao; import com.atguigu.pojo.OrderItem; public interface OrderItemDao { public int saveOrderItem(OrderItem orderItem); }
创建impl/OrderItemDaoImpl
package com.atguigu.dao.impl; import com.atguigu.dao.OrderItemDao; import com.atguigu.pojo.OrderItem; public class OrderItemDaoImpl extends BaseDao implements OrderItemDao { @Override public int saveOrderItem(OrderItem orderItem) { String sql="insert into t_order_item(name,count,price,total_price,order_id)values(?,?,?,?,?)"; return update(sql,orderItem.getName(),orderItem.getCount(),orderItem.getPrice(),orderItem.getTotalPrice(),orderItem.getUserId()); } }
测试 test/OrderDaoTest
package com.atguigu.test; import com.atguigu.dao.OrderDao; import com.atguigu.dao.impl.OrderDaoImpl; import com.atguigu.pojo.Order; import org.junit.Test; import java.math.BigDecimal; import java.util.Date; public class OrderDaoTest { @Test public void saveOrder() { OrderDao orderDao=new OrderDaoImpl(); orderDao.saveOrder(new Order("1234567890",new Date(),new BigDecimal(100),0,1)); } }
创建test/OrderItemDaoTest
package com.atguigu.test; import com.atguigu.dao.OrderItemDao; import com.atguigu.dao.impl.OrderItemDaoImpl; import com.atguigu.pojo.OrderItem; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.*; public class OrderItemDaoTest { @Test public void saveOrderItem() { OrderItemDao orderItemDao=new OrderItemDaoImpl(); orderItemDao.saveOrderItem(new OrderItem(null,"java",1,new BigDecimal(100),new BigDecimal(100),"1234657890")); orderItemDao.saveOrderItem(new OrderItem(null,"js",2,new BigDecimal(100),new BigDecimal(200),"1234657890")); orderItemDao.saveOrderItem(new OrderItem(null,"Netty",1,new BigDecimal(100),new BigDecimal(100),"1234657890")); } }
2.2.4、编写订单模块的Service和测试
创建service/OrderService
package com.atguigu.service; import com.atguigu.pojo.Cart; public interface OrderService { public String createOrder(Cart cart,Integer userId); }
创建impl/OrderServiceImpl
package com.atguigu.service.impl; import com.atguigu.dao.OrderDao; import com.atguigu.dao.OrderItemDao; import com.atguigu.dao.impl.OrderDaoImpl; import com.atguigu.dao.impl.OrderItemDaoImpl; import com.atguigu.pojo.Cart; import com.atguigu.pojo.CartItem; import com.atguigu.pojo.Order; import com.atguigu.pojo.OrderItem; import com.atguigu.service.OrderService; import java.util.Date; import java.util.Map; public class OrderServiceImpl implements OrderService { private OrderDao orderDao =new OrderDaoImpl(); private OrderItemDao orderItemDao=new OrderItemDaoImpl(); @Override public String createOrder(Cart cart, Integer userId) { //订单号==唯一性 String orderId=System.currentTimeMillis()+""+userId; //创建一个订单对象 Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId); //保存订单 orderDao.saveOrder(order); //遍历购物车中每一个商品项转换为订单保存到数据库 for (Map.Entry<Integer, CartItem>entry:cart.getItems().entrySet()) { //获取购物车每一个商品项 CartItem cartItem=entry.getValue(); //转换为订单 OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId); //保存到数据库 orderItemDao.saveOrderItem(orderItem); } //清空购物车 cart.clear(); return orderId; } }
测试 test/OrderServiceTest
package com.atguigu.test; import com.atguigu.pojo.Cart; import com.atguigu.pojo.CartItem; import com.atguigu.service.OrderService; import com.atguigu.service.impl.OrderServiceImpl; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.*; public class OrderServiceTest { @Test public void createOrder() { Cart cart=new Cart(); cart.addItem(new CartItem(1,"java",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(1,"java",1,new BigDecimal(1000),new BigDecimal(1000))); cart.addItem(new CartItem(2,"数据结构与算法",1,new BigDecimal(100),new BigDecimal(100))); OrderService orderService=new OrderServiceImpl(); System.out.println("订单号是:"+orderService.createOrder(cart, 1)); } }
2.2.5 结账功能的实现
创建 web/OrderServlet
package com.atguigu.web; import com.atguigu.pojo.Cart; import com.atguigu.pojo.User; import com.atguigu.service.OrderService; import com.atguigu.service.impl.OrderServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class OrderServlet extends BaseServlet{ private OrderService orderService=new OrderServiceImpl(); /** * 生成订单 * @param req * @param resp * @throws ServletException * @throws IOException */ protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //先获取Cart购物车对象 Cart cart = (Cart) req.getSession().getAttribute("cart"); //获取Userid User loginUser = (User) req.getSession().getAttribute("user"); if (loginUser==null){ req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp); return; } Integer userId = loginUser.getId(); //调用orderservice.createorder(cart,userid);生成订单 String orderId = orderService.createOrder(cart, userId); // req.setAttribute("orderId",orderId); //请求转发至pages/cart/checkout.jsp // req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req,resp); req.getSession().setAttribute("orderId",orderId); resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp"); } }
修改 cart.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/8/21 Time: 下午 02:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>购物车</title> <%--静态包含 base标签,css样式,jquery文件 --%> <%@ include file="/pages/common/head.jsp"%> <script type="text/javascript"> $(function (){ //给删除绑定单击事件 $("a.deleteItem").click(function (){ return confirm("你确定要删除吗【"+$(this).parent().parent().find("td:first").text()+"】?"); }); //给清空购物车绑定单击事件 $("#clearCart").click(function (){ return confirm("你确定要清空购物车吗?"); }); //给输入框失去焦点事件 === onchange 内容发生改变事件 $(".updateCount").change(function (){ //获取商品名称 var name=$(this).parent().parent().find("td:first").text(); //获取商品id var id=$(this).attr("bookId"); //获取商品数量 var count=this.value; if (confirm("你确定要将【"+name+"】商品修改数量为:"+count+"吗?")){ //发起请求。给服务器保存修改 location.href="http://localhost:8080/book/cartServlet?action=updateCount&count="+count+"&id="+id; }else { //defaultValue属性是表单项Dom对象的属性。它表示默认的value属性值。 this.value=this.defaultValue; } }); }); </script> </head> <body> <div id="header"> <img class="logo_img" alt="" src="static/img/logo.gif"> <span class="wel_word">购物车</span> <%-- 静态包含登录成功之后的菜单--%> <%@ include file="/pages/common/login_sucess_menu.jsp"%> </div> <div id="main"> <table> <tr> <td>商品名称</td> <td>数量</td> <td>单价</td> <td>金额</td> <td>操作</td> </tr> <c:if test="${empty sessionScope.cart.items}"> <%-- 如果购物车为空的情况 --%> <td colspan="5"><a href="index.jsp"> 亲,当前购物车为空!快跟小伙伴们去浏览商品吧!!!</a></td> </c:if> <c:if test="${not empty sessionScope.cart.items}"> <%-- 如果购物车非空的情况 --%> <c:forEach items="${sessionScope.cart.items}" var="entry"> <tr> <td>${entry.value.name}</td> <td> <input class="updateCount" style="width: 80px" bookId="${entry.value.id}" type="text" value="${entry.value.count}"> </td> <td>${entry.value.price}</td> <td>${entry.value.totalPrice}</td> <td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${entry.value.id}">删除</a></td> </tr> </c:forEach> </c:if> </table> <c:if test="${not empty sessionScope.cart.items}"> <div class="cart_info"> <span class="cart_span">购物车中共有<span class="b_count">${sessionScope.cart.totalCount}</span>件商品</span> <span class="cart_span">总金额<span class="b_price">${sessionScope.cart.totalPrice}</span>元</span> <span class="cart_span"><a id="clearCart" href="cartServlet?action=clear">清空购物车</a></span> <span class="cart span"><a href="orderServlet?action=createOrder">去结账</a></span> </div> </c:if> </div> <%--静态包含页脚内容--%> <%@include file="/pages/common/footer.jsp"%> </body> </html>
修改 checkout.jsp
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/8/21 Time: 下午 02:49 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>结算页面</title> <%--静态包含 base标签,css样式,jquery文件 --%> <%@ include file="/pages/common/head.jsp"%> <style type="text/css"> h1 { text-align: center; margin-top: 200px; } </style> </head> <body> <div id="header"> <img class="logo_img" alt="" src="../../static/img/logo.gif"> <span class="wel_word">结算</span> <%-- 静态包含登录成功之后的菜单--%> <%@ include file="/pages/common/login_sucess_menu.jsp"%> </div> <div id="main"> <%-- <h1>你的订单已结算,订单号为:${requestScope.orderId}</h1>--%> <h1>你的订单已结算,订单号为:${sessionScope.orderId}</h1> </div> <%--静态包含页脚内容--%> <%@include file="/pages/common/footer.jsp"%> </body> </html>
修改 OrderServiceImpl 以解决库存销量bug
package com.atguigu.service.impl; import com.atguigu.dao.BookDao; import com.atguigu.dao.OrderDao; import com.atguigu.dao.OrderItemDao; import com.atguigu.dao.impl.BookDaoImpl; import com.atguigu.dao.impl.OrderDaoImpl; import com.atguigu.dao.impl.OrderItemDaoImpl; import com.atguigu.pojo.*; import com.atguigu.service.OrderService; import java.util.Date; import java.util.Map; public class OrderServiceImpl implements OrderService { private OrderDao orderDao =new OrderDaoImpl(); private OrderItemDao orderItemDao=new OrderItemDaoImpl(); private BookDao bookDao=new BookDaoImpl(); @Override public String createOrder(Cart cart, Integer userId) { //订单号==唯一性 String orderId=System.currentTimeMillis()+""+userId; //创建一个订单对象 Order order=new Order(orderId,new Date(),cart.getTotalPrice(),0,userId); //保存订单 orderDao.saveOrder(order); //遍历购物车中每一个商品项转换为订单保存到数据库 for (Map.Entry<Integer, CartItem>entry:cart.getItems().entrySet()) { //获取购物车每一个商品项 CartItem cartItem=entry.getValue(); //转换为订单 OrderItem orderItem=new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),orderId); //保存到数据库 orderItemDao.saveOrderItem(orderItem); //更新库存和销量 Book book = bookDao.queryBookById(cartItem.getId()); book.setSales(book.getSales()+cartItem.getCount()); book.setStock(book.getStock()-cartItem.getCount()); bookDao.updateBook(book); } //清空购物车 cart.clear(); return orderId; } }