This article continues to share with you the shopping cart module in the javaweb bookstore for your reference. The specific content is as follows
Shopping cart storage
Save in session Save in cookies Save in database
1. Create related classes
Shopping cart structure:
CartItem: Shopping cart entry, containing books and quantity
Cart: Shopping cart, including a map
/** * Shopping cart class*/public class Cart { private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>(); /** * Calculate the total* @return */ public double getTotal() { // Total = sum of subtotals of all entries BigDecimal total = new BigDecimal("0"); for(CartItem cartItem : map.values()) { BigDecimal subtotal = new BigDecimal("" + cartItem.getSubtotal()); total = total.add(subtotal); } return total.doubleValue(); } /** * Add an entry to the car* @param cartItem */ public void add(CartItem cartItem) { if(map.containsKey(cartItem.getBook().getBid())) {//Judge whether the entry exists in the original car CartItem _cartItem = map.get(cartItem.getBook().getBid());//Return to the original entry_cartItem.setCount(_cartItem.getCount() + cartItem.getCount());//Set the number of old entries to its own number + the number of new entries map.put(cartItem.getBook().getBid(), _cartItem); } else { map.put(cartItem.getBook().getBid(), cartItem); } } /** * Clear all entries*/ public void clear() { map.clear(); } /** * Delete the specified entries* @param bid */ public void delete(String bid) { map.remove(bid); } /** * Get all entries* @return */ public Collection<CartItem> getCartItems() { return map.values(); }} /** * Shopping cart entry class* */public class CartItem { private Book book;// product private int count;// quantity/** * subtotal method* @return * Handled binary operation error problem*/ public double getSubtotal() {// subtotal method, but it has no corresponding member! BigDecimal d1 = new BigDecimal(book.getPrice() + ""); BigDecimal d2 = new BigDecimal(count + ""); return d1.multiply(d2).doubleValue(); } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getCount() { return count; } public void setCount(int count) { this.count = count; }}2. Add shopping cart entry
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Shopping cart list</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"> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --><style type="text/css"> * { font-size: 11pt; } div { margin:20px; border: solid 2px gray; width: 150px; height: 150px; text-align: center; } li { margin: 10px; } #buy { background: url(<c:url value='/images/all.png'/>) no-repeat; display: inline-block; background-position: 0 -902px; margin-left: 30px; height: 36px; width: 146px; } #buy:HOVER { background: url(<c:url value='/images/all.png'/>) no-repeat; display: inline-block; background-position: 0 -938px; margin-left: 30px; height: 36px; width: 146px; }</style> </head> <body><h1>Shopping cart</h1><c:choose> <%-- If there is no car, or the content collection of the car is 0-length-%> <c:when test="${empty sessionScope.cart or fn:length(sessionScope.cart.cartItems) eq 0}"> <img src="<c:url value='/images/cart.png'////"/> </c:when> <c:otherwise><table cellpacing="0" background="black"> <tr> <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900"> <a href="<c:url value='/CartServlet?method=clear'//"> Clear the cart</a> </td> </tr> <tr> <th>Picture</th> <th>Book Title</th> <th>Author</th> <th>Unit Price</th> <th>Quantity</th> <th>Subtotal</th> <th>Operation</th> </tr><c:forEach items="${sessionScope.cart.cartItems }" var="cartItem"> <tr> <td><div><img src="<c:url value='/${cartItem.book.image }'//"/></div></td> <td>${cartItem.book.bname }</td> <td>${cartItem.book.author }</td> <td>${cartItem.book.price } Yuan</td> <td>${cartItem.count }</td> <td>${cartItem.subtotal } Yuan</td> <td><a href="<c:url value='/CartServlet?method=delete&bid=${cartItem.book.bid }'/>">Delete</a></td> </td> </td> </tr></c:forEach> <ttr> <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900"> Total: ${sessionScope.cart.total } Yuan</td> </tr> <tr> <td colspan="7" align="right" style="font-size: 15pt; font-weight: 900"> <a id="buy" href="<c:url value='/OrderServlet?method=add'/>"></a> </td> </tr></table> </c:otherwise></c:choose> </body></html> public class CartServlet extends BaseServlet { /** * Add shopping entry* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get the car* 2. Get the entry (get the book and quantity) * 3. Add the entry to the car*/ /* * 1. Get the car*/ Cart cart = (Cart)request.getSession().getAttribute("cart"); /* * The form passes only the bid and the quantity* 2. Get the entry* > Get the book and the quantity* > First get the bid of the book, and then we need to query the database through the bid to get the Book * > There is */ String bid = request.getParameter("bid"); Book book = new BookService().load(bid); int count = Integer.parseInt(request.getParameter("count")); CartItem cartItem = new CartItem(); cartItem.setBook(book); cartItem.setCount(count); /* * 3. Add the entry to the car*/ cart.add(cartItem); return "f:/jsps/cart/list.jsp"; } /** * Clear the shopping entry* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 1. Get the car* 2. Set the car's clear */ Cart cart = (Cart)request.getSession().getAttribute("cart"); cart.clear(); return "f:/jsps/cart/list.jsp"; } /** * Delete shopping entries* @param request * @param response * @return * @throws ServletException * @throws IOException */ public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get the car* 2. Get the bid to be deleted */ Cart cart = (Cart)request.getSession().getAttribute("cart"); String bid = request.getParameter("bid"); cart.delete(bid); return "f:/jsps/cart/list.jsp"; }}3. Clear the entry
4. Delete the shopping cart entry
5. My shopping cart
There is a link in top.jsp: My shopping cart
My cart accesses directly /jsps/cart/list.jsp and it displays all entries of the cart in session.
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.