This article shares the specific code of the shopping cart module for your reference. The specific content is as follows
It is not a session or a cookie, but a table
> Add a shopping entry
> Modify the number of shopping entries
> Delete an entry
> Batch deletion of entries
> My shopping cart, that is, query items by user
> Query the checked entries
1. Data table
The code copy is as follows: insert into `t_cartitem`(`cartItemId`,`quantity`,`bid`,`uid`,`orderBy`) values ('B8939FC55131469CAB11E3924D40185B',1,'CE01F15D435A4C51B0AD8202A318DCA7','xxx',11);
2.CartItem
public class CartItem { private String cartItemId;// primary key private int quantity;// quantity private Book book;// book corresponding to the entry private User user;// user to which the user// Add subtotal method public double getSubtotal() { /* * There will be no errors when using BigDecimal* Requires the String type constructor to be used*/ BigDecimal b1 = new BigDecimal(book.getCurrPrice() + ""); BigDecimal b2 = new BigDecimal(quantity + ""); BigDecimal b3 = b1.multiply(b2); return b3.doubleValue(); } public String getCartItemId() { return cartItemId; } public void setCartItemId(String cartItemId) { this.cartItemId = cartItemId; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public User getUser() { return user; } public void setUser(User user) { this.user = user; }}Tips: There will be no errors in rounding BigDecimal in Java
// Add subtotal method public double getSubtotal() { /* * There will be no error when using BigDecimal* Requires String type constructor to be used*/ BigDecimal b1 = new BigDecimal(book.getCurrPrice() + ""); BigDecimal b2 = new BigDecimal(quantity + ""); BigDecimal b3 = b1.multiply(b2); return b3.doubleValue();}3. Check the shopping cart entry through users
Each entry in my shopping cart entry needs to display the list price of the picture book, which means that multiple tables are required
public List<CartItem> findByUser(String uid) throws SQLException { String sql = "select * from t_cartitem c, t_book b where c.bid=b.bid and uid=? order by c.orderBy"; List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler(), uid); return toCartItemList(mapList);}4. Add shopping cart entries-----Add
jsp
<div> <form id="form1" action="<c:url value='/CartItemServlet'//>" method="post"> <input type="hidden" name="method" value="add"/> <input type="hidden" name="bid" value="${book.bid }"/> I want to buy: <input id="cnt" type="text" name="quantity" value="1"/> </form> <a id="btn" href="javascript:$('#form1').submit();"></a></div>CartItemServlet
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* * 1. Encapsulate form data to CartItem(bid, quantity) */ Map map = req.getParameterMap(); CartItem cartItem = CommonUtils.toBean(map, CartItem.class); Book book = CommonUtils.toBean(map, Book.class); User user = (User)req.getSession().getAttribute("sessionUser"); cartItem.setBook(book); cartItem.setUser(user); cartItemService.add(cartItem); return myCart(req, resp);}CartItemService
public void add(CartItem cartItem) { try { /* * 1. Use uid and bid to query whether this entry exists in the database*/ CartItem _cartItem = cartItemDao.findByUidAndBid( cartItem.getUser().getUid(), cartItem.getBook().getBid()); if(_cartItem == null) {//If there was no such entry, add the entry cartItem.setCartItemId(CommonUtils.uuid()); cartItemDao.addCartItem(cartItem); } else {//If there was this entry, modify the number// Use the original quantity and the number of new entries to be used as the new quantity int quantity = cartItem.getQuantity() + _cartItem.getQuantity(); // Modify the quantity of this old entry cartItemDao.updateQuantity(_cartItem.getCartItemId(), quantity); } } catch(Exception e) { throw new RuntimeException(e); }}CartItemDao
public void addCartItem(CartItem cartItem) throws SQLException { String sql = "insert into t_cartitem(cartItemId, quantity, bid, uid)" + " values(?,?,?,?)"; Object[] params = {cartItem.getCartItemId(), cartItem.getQuantity(), cartItem.getBid(), cartItem.getUser().getUid()}; qr.update(sql, params);}5. Shopping cart module page javascript----check
Calculate the total
Add click event to select all
Add click event to the checkbox for all entries
Add click event to the minus sign
Add click event to the plus sign
Batch Delete
list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>cartlist.jsp</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="<c:url value='/jquery/jquery-1.5.1.js'/>"></script> <script src="<c:url value='/js/round.js'/>"></script> <link rel="stylesheet" type="text/css" href="<c:url value='/jsps/css/cart/list.css'///>"><script type="text/javascript">$(function() { showTotal();//calculate the total/* Add click event to select all*/ $("#selectAll").click(function() { /* 1. Get the status of select all*/ var bool = $("#selectAll").attr("checked"); /* 2. Synchronize the checkboxes of all entries with the selected all status*/ setItemCheckBox(bool); /* 3. Synchronize the checkout button with the selected all*/ setJieSuan(bool); /* 4. Recalculate the total*/ showTotal(); }); /* Add click event to the checkboxes of all entries*/ $(":checkbox[name=checkboxBtn]").click(function() { var all = $(":checkbox[name=checkboxBtn]").length;//The number of all entries var select = $(":checkbox[name=checkboxBtn][checked=true]").length;//Get the number of all selected entries if(all == select) {//All $("#selectAll").attr("checked", true);//Check the checkbox all check box setJieSuan(true);//Make the checkout button valid} else if(select == 0) {//No one selected $("#selectAll").attr("checked", false);//Cancel all setJieSuan(false);//Cancel checkout} else { $("#selectAll").attr("checked", false);//Cancel all setJieSuan(false);//Cancel checkout} else { $("#selectAll").attr("checked", false);//Cancel all setJieSuan(true);//Let settlement be valid} showTotal();//Recalculate total}); /* Add click event to the minus sign*/ $(".jian").click(function() { // Get cartItemId var id = $(this).attr("id").substring(0, 32); // Get the quantity in the input box var quantity = $("#" + id + "Quantity").val(); // Determine whether the current quantity is 1. If it is 1, it is not modifying the quantity, but deleting it. if(quantity == 1) { if(confirm("Do you really want to delete the entry?")) { location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + id; } } else { sendUpdateQuantity(id, quantity-1); } }); // Add click event $(".jia").click(function() { // Get cartItemId var id = $(this).attr("id").substring(0, 32); // Get the number in the input box var quantity = $("#" + id + "Quantity").val(); sendUpdateQuantity(id, Number(quantity)+1); });});// Request the server and modify the quantity. function sendUpdateQuantity(id, quantity) { $.ajax({ async:false, cache:false, url:"/goods/CartItemServlet", data:{method:"updateQuantity",cartItemId:id,quantity:quantity}, type:"POST", dataType:"json", success:function(result) { //1. Modify quantity $("#" + id + "Quantity").val(result.quantity); //2. Modify subtotal $("#" + id + "Subtotal").text(result.subtotal); //3. Recalculate the total showTotal(); } });}/* * Calculate the total*/function showTotal() { var total = 0; /* 1. Get all checked entries check boxes! Loop traversal */ $(":checkbox[name=checkboxBtn][checked=true]").each(function() { //2. Get the value of the check box, that is, the prefix of other elements var id = $(this).val(); //3. Then find the subtotal element through the prefix and get its text var text = $("#" + id + "Subtotal").text(); //4. Calculate total += Number(text); }); // 5. Display the total on the total element $("#total").text(round(total, 2)); // The function of the round() function is to retain total 2 bits}/* * Set the check button for all entries in uniform */function setItemCheckBox(bool) { $(":checkbox[name=checkboxBtn]").attr("checked", bool);}/* * Set checkout button style*/function setJieSuan(bool) { if(bool) { $("#jiesuan").removeClass("kill").addClass("jiesuan"); $("#jiesuan").unbind("click");//Undo all click events of the current element} else { $("#jiesuan").removeClass("jiesuan").addClass("kill"); $("#jiesuan").click(function() {return false;}); } }/* * Batch delete*/function batchDelete() { // 1. Get the checkboxes for all selected entries // 2. Create an array and add the values of all selected checkboxes to the array // 3. Specify the location as CartItemServlet, parameter method=batchDelete, parameter cartItemIds= toString() of the array var cartItemIdArray = new Array(); $(":checkbox[name=checkboxBtn][checked=true]").each(function() { cartItemIdArray.push($(this).val());//Add the value of the checkbox to the array}); location = "/goods/CartItemServlet?method=batchDelete&cartItemIdArray;}/* * Checkout*/function jiesuan() { // 1. Get the ids of all selected entries and put them in the array var cartItemIdArray = new Array(); $(":checkbox[name=checkboxBtn][checked=true]").each(function() { cartItemIdArray.push($(this).val());// Add the value of the checkbox to the array}); // 2. Submit the value of the array toString() and then assign it to the cartItemIds of the form. $("#cartItemIds").val(cartItemIdArray.toString()); // Save the total value to the form $("#hiddenTotal").val($("#total").text()); // 3. Submit this form $("#jieSuanForm").submit();}</script> </head> <body><c:choose> <c:when test="${empty cartItemList }"> <table align="center" cellpadding="0" cellpacing="0"> <tr> <td align="right"> <img align="top" src="<c:url value='/images/icon_empty.png'////"/> </td> <td> <span>There is no products in your cart</span> </td> </tr> </table> </c:when> <c:otherwise><table align="center" cellpadding="0" cellpacing="0"> <tr align="center" bgcolor="#efeae5"> <td align="left"> <input type="checkbox" id="selectAll" checked="checked"/><label for="selectAll">Select all</label> </td> <td colspan="2">Product name</td> <td>Unit price</td> <td>Quantity</td> <td>Subtotal</td> <td>Operation</td> </td> </td> </tr><c:forEach items="${cartItemList }" var="cartItem"> <tr align="center"> <td align="left"> <input value="${cartItem.cartItemId }" type="checkbox" name="checkboxBtn" checked="checked"/> </td> <td align="left"> <a href="<c:url value='/jsps/book/desc.jsp'/>"><img align="top" src="<c:url value='/${cartItem.book.image_b }'///>"/> </td> <td align="left"> <a href="<c:url value='/jsps/book/desc.jsp'/>"><span>${cartItem.book.bname }</span></a> </td> <td><span>${cartItem.book.currPrice }</span></span></td> <td> <a id="${cartItem.cartItemId }Jian"></a><input readonly="readonly" id="${cartItem.cartItemId }Quantity" type="text" value="${cartItem.quantity }"/><a id="${cartItem.cartItemId }Jia"></a> </td> <td> <span>¥<span id="${cartItem.cartItemId }Subtotal">${cartItem.subtotal }</span></span> </td> <td> <a href="<c:url value='/CartItemServlet?method=batchDelete&cartItemIds=${cartItem.cartItemId }'/>">Delete</a> </td> </td> </tr></c:forEach> <tr> <td colspan="4"> <a href="javascript:batchDelete();">Batch Delete</a> </td> <td colspan="3" align="right"> <span>Total: </span><span>¥<span id="total"></span></span> </td> </tr> <tr> <td colspan="7" align="right"> <a href="javascript:jiesuan();" id="jiesuan"></a> </td> </tr></table> <form id="jieSuanForm" action="<c:url value='/CartItemServlet'//>" method="post"> <input type="hidden" name="cartItemIds" id="cartItemIds"/> <input type="hidden" name="total" id="hiddenTotal"/> <input type="hidden" name="method" value="loadCartItems"/> </form> </c:otherwise></c:choose> </body></html>Tips: Round round.js in js
// 5. Display the total on the total element $("#total").text(round(total, 2));//The function of the round() function is to retain 2 bits of total6. Batch deletion function----Delete
jsp
function batchDelete() { // 1. Get the checkboxes for all selected entries // 2. Create an array and add the values of all selected checkboxes to the array // 3. Specify the location as CartItemServlet, parameter method=batchDelete, parameter cartItemIds= toString() of the array var cartItemIdArray = new Array(); $(":checkbox[name=checkboxBtn][checked=true]").each(function() { cartItemIdArray.push($(this).val());//Add the value of the checkbox to the array}); location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + cartItemIdArray;}Delete one
if(quantity == 1) { if(confirm("Do you really want to delete the entry?")) { location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + id; }} else {7. Modify the quantity-----Modify
jsp
// Request the server and modify the number. function sendUpdateQuantity(id, quantity) { $.ajax({ async:false, cache:false, url:"/goods/CartItemServlet", data:{method:"updateQuantity",cartItemId:id,quantity:quantity}, type:"POST", dataType:"json", success:function(result) { //1. Modify quantity $("#" + id + "Quantity").val(result.quantity); //2. Modify subtotal $("#" + id + "Subtotal").text(result.subtotal); //3. Recalculate the total showTotal(); } });}servlet
public String updateQuantity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cartItemId = req.getParameter("cartItemId"); int quantity = Integer.parseInt(req.getParameter("quantity")); CartItem cartItem = cartItemService.updateQuantity(cartItemId, quantity); // Return a json object to the client StringBuilder sb = new StringBuilder("{"); sb.append("/"quantity/"").append(":").append(cartItem.getQuantity()); sb.append(","); sb.append("/"subtotal/"").append(":").append(cartItem.getSubtotal()); sb.append("}"); resp.getWriter().print(sb); return null;}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.