Este artículo continúa compartiendo con usted el módulo del carrito de compras en la librería Javaweb para su referencia. El contenido específico es el siguiente
Almacenamiento del carrito de compras
Guardar en la sesión Guardar en cookies Guardar en la base de datos
1. Crear clases relacionadas
Estructura del carrito de compras:
Cartitem: entrada de carrito de compras, que contiene libros y cantidad
Cart: carrito de compras, incluido un mapa
/*** clase de carrito de compras*/Cart de clase pública {Map privado <String, Cartitem> map = new LinkedHashMap <String, Cartitem> (); / *** Calcule el total* @return*/ public doble getTotal () {// total = suma de subtotales de todas las entradas bigDecimal Total = new BigDecimal ("0"); para (Cartitem Cartitem: map.Values ()) {bigDecimal subtotal = new BigDecimal ("" + Cartitem.getSubTotal ()); Total = Total.Add (Subtotal); } return Total.DoubleValue (); }/*** Agregue una entrada al automóvil* @param Cartitem*/public void add (Cartitem Cartitem) {if (map.ContainsKey (Cartitem.getBook (). GetBid ())) {// juzga si la entrada existe en el carrito de automóvil original _Cartitem = map.get (Cartitem.getBook (). Getbid ()); entry_cartitem.setCount (_Cartitem.getCount () + Cartitem.getCount ()); // Establezca el número de entradas antiguas en su propio número + el número de nuevas entradas map.put (Cartitem.getBook (). getBid (), _Cartitem); } else {map.put (Cartitem.getBook (). getBid (), Cartitem); }} / *** Borrar todas las entradas* / public void clear () {map.clear (); } / *** Eliminar las entradas especificadas* @param bid* / public void Delete (bid de cadena) {map.remove (bid); } / *** Obtenga todas las entradas* @return* / public Collection <artitem> getCartitems () {return map.values (); }} /*** clase de entrada de carrito de compras**/public class Cartitem {Libro privado Libro de libros;/Producto Private int count; // Cantidad/*** Método subtotal* @return* Problema de error de operación binaria manejada*/public Double getSubTotal () {// Método subtotal, ¡pero no tiene miembro correspondiente! BigDecimal d1 = new BigDecimal (book.getPrice () + ""); BigDecimal d2 = new BigDecimal (Count + ""); return d1.multiply (d2) .DoubleValue (); } Libro público getBook () {Book de retorno; } public void setbook (libro de libro) {this.book = book; } public int getCount () {return Count; } public void setCount (int count) {this.count = count; }}2. Agregue la entrada del carrito de compras
<%@ page lenguaje = "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 público "-// w3c // dtd html 4.01 Transitional // en "> <html> <fead> <title> Compre Cart List </title> <meta http-equiv =" pragma "content =" no-cache "> <meta http-equiv =" cache-confuntrol "content =" no cache "> <meta http-oquiv =" expira "contenido =" 0 "> <meta http-equtp =" keys "keys" Content = "Keyword1, Keyword2, Keyword3"> <meta http-equiv = "Descripción" Content = "Esta es mi página"> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <!-<link rel = "stylesheet" type = "text/css" href = "styles.csssssss"---<sylyles type = "text/css" href = "styles.cssssss"---<sylyles "styles.syles.cs.css.css. type = "text/css"> * {font-size: 11pt; } div {margen: 20px; borde: sólido 2px gris; Ancho: 150px; Altura: 150px; Text-Align: Center; } li {margen: 10px; } #Buy {fondo: url (<c: url value = '/images/all.png'/>) no-repeat; Pantalla: bloque en línea; Posición de fondo: 0 -902px; margen-izquierda: 30px; Altura: 36px; Ancho: 146px; } #Buy: Hover {fondo: url (<c: url value = '/images/all.png'/>) no-repeat; Pantalla: bloque en línea; Posición de fondo: 0 -938px; margen-izquierda: 30px; Altura: 36px; Ancho: 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/card.png' //// "/> </c: When> <c: lo contrario> <table cellPacing =" 0 "en segundo plano =" negro "> <tr> <td colspan =" 7 "align =" right "style =" font-size: 15pt-weight: 900 "> <a href =" <c: url value = '/Cartservlet? Cart </a> </td> </tr> <tr> <th> Imagen </th> <th> Título del libro </th> <th> Autor </th> <th> Price Unit </th> <th> Cantidad </th> <th> Subtotal </th> <th> Operation </th> </tr> <c: items de foreach = "$ {sessionscope.cart.cartitems. var = "Cartitem"> <tr> <td> <div> <img src = "<c: url value = '/$ {Cartitem.book.image}' //"/> </div> </td> <td> $ {Cartitem.book.bnEn <TD> $ {cartitem.book.price} yuan </td> <td> $ {cartitem.count} </td> <td> $ {cartitem.subtotal} yuan </td> <td> <a href = "<c: url valor = '/cartServlet? } '/> "> Eliminar </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: de lo contrario> </c: elija> </body> </html> Public Class CartServlet extiende BaseServlet { /** * Agregar entrada de compras * @param solicitud * @param Respuesta * @return * @throws servletException * @throws ioexception * /public string add (httpservletRequest solicitud, httpservletResponse respuesta) lanza servletException, ioexception { / * * * 1. Obtener el cuidado * 2. Obtener la entrada (obtenga la entrada (obtenga la entrada y obtenga la entrada (obtenga la entrada y obtenga la entrada (obtenga el Libro) (obtenga el Libro) (obtenga la entrada. la entrada al automóvil*//** 1. Obtenga el automóvil*/ carrito de carry = (carto) request.getSession (). getAttribute ("Cart"); /** El formulario pasa solo la oferta y la cantidad* 2. Obtenga la entrada*> Obtenga el libro y la cantidad*> Primero obtenga la oferta del libro, y luego necesitamos consultar la base de datos a través de la oferta para obtener el libro*> Hay*/ String bid = request.getParameter ("Bid"); Libro book = new Bookservice (). Load (BID); int count = Integer.ParseInt (request.getParameter ("Count")); Cartitem Cartitem = new Cartitem (); Cartitem.setbook (libro); Cartitem.setCount (recuento); /** 3. Agregue la entrada al automóvil*/ CART.Add (Cartitem); return "f: /jsps/cart/list.jsp"; } / ** * Borre la entrada de compras * @param solicitud * @param respuesta * @return * @throws servletException * @throws ioexception * / public string clare (httpservletRequest solicitud, respuesta httpServletResponse) lanza ServletException, ioException { / ** * 1. Obtenga el automóvil * 2. Establezca el CARS CARRE * / CART CART = CART = CART = CART = CART = CART = CART = CART = CART = CART = CART = CART = CART = CART = (CART) request.getSession (). GetAttribute ("carro"); CART.CLEAR (); return "f: /jsps/cart/list.jsp"; } / ** * Eliminar las entradas de compras * @param Solicitud * @param respuesta * @return * @throws servletException * @throws ioexception * / public string delete (httpservletRequest solicitud, httpServletResponse respuesta) lanza servletException, ioexception { / * * 1. Obtenga el automóvil * 2. Obtener la oferta para ser deeted * / Cart Cart = (CART) request.getSession (). GetAttribute ("carro"); Cadena bid = request.getParameter ("bid"); CART.delete (oferta); return "f: /jsps/cart/list.jsp"; }}3. Borre la entrada
4. Eliminar la entrada del carrito de compras
5. Mi carrito de compras
Hay un enlace en top.jsp: mi carrito de compras
Mi carrito accede directamente a /jsps/cart/list.jsp y muestra todas las entradas del carrito en la sesión.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.