Este artigo continua a compartilhar com você o módulo de carrinho de compras na livraria Javaweb para sua referência. O conteúdo específico é o seguinte
Armazenamento de carrinho de compras
Salvar na sessão Salvar em cookies salvar no banco de dados
1. Crie classes relacionadas
Estrutura do carrinho de compras:
Cartitem: entrada do carrinho de compras, contendo livros e quantidade
CART: Carrinho de compras, incluindo um mapa
/*** Classe de carrinho de compras*/Classe public CART {private mapa <String, CartItem> map = new LinkedHashmap <String, CartItem> (); / *** Calcule o total* @return*/ public duplo gettotal () {// total = soma dos subtotais de todas as entradas bigdecimal total = new bigDecimal ("0"); para (CartItem CartItem: map.Values ()) {BigDecimal subtotal = new BigDecimal ("" + CartItem.getSubtotal ()); total = total.add (subtotal); } retornar total.doubleValue (); }/*** Adicione uma entrada ao carro* @param CARTItem*/public void add (CartItem CartItem) {if (map.containsKey (cartIm.getBook (). Getbid ())) {// julga a entrada. ENTRING_CARTITEM.SETCOUNT (_cartItem.getCount () + CartIm.getCount ()); // Defina o número de entradas antigas para seu próprio número + o número de novas entradas map.put (cartItem.getbook (). getbid (), _cartItem); } else {map.put (cartItem.getBook (). getbid (), cartItem); }} / *** Limpe todas as entradas* / public void clear () {map.clear (); } / *** Exclua as entradas especificadas* @param bid* / public void delete (string bid) {map.remove (bid); } / *** Obtenha todas as entradas* @return* / public collection <TetItem> getCartItems () {return map.values (); }} /** Bigdecimal d1 = novo bigdecimal (book.getprice () + ""); Bigdecimal d2 = novo bigdecimal (contagem + ""); return d1.multiply (d2) .doubleValue (); } public book getBook () {return book; } public void Setbook (livro de livros) {this.book = book; } public int getCount () {Return Count; } public void setCount (int conting) {this.count = count; }}2. Adicione a entrada do carrinho de compras
<%@ Page Language = "java" import = "java.util. uri = "http://java.sun.com/jsp/jstl/fmt" %> < %@ taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %> <! Transitória // pt "> <html> <head> <title> Lista de carrinhos de compras </ititure> <meta http-equiv =" Pragma "content =" no-cache "> <meta http-equiv =" cache-controle "content =" no-cache "> <meta http-equiv =" expires " 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; borda: sólido 2px cinza; Largura: 150px; Altura: 150px; Alinhamento de texto: centro; } li {margem: 10px; } #buy {Background: url (<c: url value = '/imagens/all.png'/>) no-repetir; Exibição: bloco embutido; Posição de fundo: 0 -902px; margem-esquerda: 30px; Altura: 36px; Largura: 146px; } #buy: hover {background: url (<c: url value = '/imagens/all.png'/>) no-repetir; Exibição: bloco embutido; Posição de fundo: 0 -938px; margem-esquerda: 30px; Altura: 36px; Largura: 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 = '/imagens/cart.png' /// "/> </c: quando> <c: caso contrário, <tabela celular (" 0 "Background =" Black "> <tr> <td colspan =" 7 "align =" right "style =" font-size: 15pt; CART </a> </td> </tr> <tr> <th> foto </th> <th> título do livro </th> <th> autor </th> <th> preço unitário </th> <th> quantidade </th> <th> subtotal </s> <ther> operação <//th> </tr> <c: para os itens itens = {sess. var = "CartItem"> <tr> <td> <div> <img src = "<c: url value = '/$ {cartIm.book.image}' //"/> </div> </td> <td> $ {Cartitem.Book.bname} </td> <t> $ {CartM. <Td> $ {CartItem.Book.price} yuan </td> <td> $ {CartItem.count} </td> <td> $ {cartItem.subtotal} yuan </td> <td> <a href = "<c: url talue = '/carriptlet? } '/> "> Delete </a> </td> </td> </td> </tr> </c: foreach> <ttr> <td colspan =" 7 "align =" right "style =" font-size: 15pt; Peso da fonte: 900 "> Total: $ {sessionscope.cart.total} yuan </td> </tr> <tr> <td colspan =" 7 "align =" right "style =" font-size: 15pt; Fonte-peso: 900 "> <a id =" compre "href =" <c: url value = '/orderServlet? Método = add'/> "> </a> </td> </tr> </ table> </c: caso contrário A classe pública CartServlet estende o BasEServlet { /** * Adicione a entrada de compras * @param request * @param Resposta * @return * @throws servletexception * @throws ioexception * /public string add (httpServLetRequest Solicitação, a solicitação de the * 1 * 1. 3. Adicione a entrada ao carro*//** 1. Obtenha o carro*/ carrinho carrinho = (carrinho) request.getSession (). GetAttribute ("carrinho"); /** O formulário passa apenas a oferta e a quantidade* 2. Obtenha a entrada*> Obtenha o livro e a quantidade*> primeiro recebe a oferta do livro, e depois precisamos consultar o banco de dados através da oferta para obter o livro*> existe*/ string bid = request.getParameter ("bid"); Livro do livro = new BookService (). LOAD (BID); int count = Integer.parseint (request.getParameter ("contagem"); CartItem CartItem = new CartItem (); CartIm.setBook (livro); CartItem.setCount (contagem); /** 3. Adicione a entrada ao carro*/ cart.add (cartem); retornar "f: /jsps/cart/list.jsp"; } / ** * Limpe a entrada de compras * @param request * @param Resposta * @return * @throws servletexception * @throws ioexception * / public string clear (httpServletRequest Solicy, httpServletResponse Response o carro * 21. (Carrinho) request.getSession (). GetAttribute ("carrinho"); Cart.clear (); retornar "f: /jsps/cart/list.jsp"; } / ** * Exclua entradas de compras * @param request * @param Resposta * @return * @throws servletexception * @throws ioexception * / public String Delete (httpServletReQuest Solicitação, httpServLeTLeSponse Response * RESPOSTO * REPORTA * 2. (Carrinho) request.getSession (). GetAttribute ("carrinho"); String bid = request.getParameter ("bid"); Cart.Delete (BID); retornar "f: /jsps/cart/list.jsp"; }}3. Limpe a entrada
4. Exclua a entrada do carrinho de compras
5. Meu carrinho de compras
Há um link em top.jsp: meu carrinho de compras
Meu carrinho acessa diretamente /jsps/cart/list.jsp e exibe todas as entradas do carrinho em sessão.
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.