Эта статья продолжает делиться с вами модулем корзины для покупок в книжном магазине Javaweb для вашей ссылки. Конкретный контент заключается в следующем
Хранение корзины для покупок
Сохранить в сеансе Сохранить в файлах cookie Сохранить в базе данных
1. Создать связанные классы
Структура корзины покупок:
Cartitem: вход в корзину по магазинам, содержащая книги и количество
Тележка: корзина, включая карту
/*** Класс корзины для покупок*/public class cart {private map <string, cartitem> map = new LinkedHashmap <string, cartitem> (); / *** Рассчитайте общую* @return*/ public double getTotal () {// total = сумма подтоталов всех записей BigDecimal Total = new BigDecimal ("0"); for (cartitem cartitem: map.values ()) {bigdecimal subtotal = new bigdecimal (" + cartitem.getsubtotal ()); общее = общее.адд (подтотальный); } return total.doublevalue (); }/*** Добавить запись в автомобиль* @param cartitem*/public void add (cartitem cartitem) {if (map.containskey (cartitem.getbook (). Getbid ())) {// Судья, существует ли запись в оригинальном автомобиле cartitem _cartitem = map.getem.getem.getbook (). intry_cartitem.setCount (_cartitem.getCount () + cartitem.getCount ()); // Установить количество старых записей на свой собственный номер + количество новых записей map.put (cartitem.getbook (). getBid (), _cartitem); } else {map.put (cartitem.getbook (). getBide (), cartitem); }} / *** Очистить все записи* / public void clear () {map.clear (); } / *** Удалить указанные записи* @param bid* / public void delete (string bid) {map.remove (bid); } / *** Получить все записи* @return* / public collection <cartitem> getCartitems () {return map.values (); }} /*** Класс корзины для покупок**/public class cartitem {private Book Book; // Продукт Product private int count; // Количество/*** Подтотальный метод* @return* Обработанная бинарная ошибка операции*/public double getSubtotal () {// Подтотальный метод, но у него нет соответствующего участника! BigDecimal D1 = новый BigDecimal (book.getPrice () + ""); BigDecimal D2 = новый BigDecimal (count + ""); return d1.multiply (d2) .doublevalue (); } public book getBook () {return book; } public void setbook (книга книги) {this.book = book; } public int getCount () {return count; } public void setCount (int count) {this.count = count; }}2. Добавить вход в корзину для покупок
<%@ 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/functs" %> <! Doctpe html public "//w3c // dtd html html htm Transitional // en "> <html> <Head> <Title> Список корзины для покупок </title> <meta http-equiv =" pragma "content =" no-cache "> <meta http-equiv =" cache-control "content =" meta-quev-quev-equiv = "expires" = "0"> <meta htt-quev-equiv = "expires" = "0". Content = "Keyword1, Keyword2, Keyword3"> <Meta http-equiv = "description" content = "Это моя страница"> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <!-<link rel = "stylessheet" type = "csss 'href =" type = "text/css"> * {font-size: 11pt; } div {margin: 20px; Граница: твердый 2PX серый; Ширина: 150px; Высота: 150px; Текст-альбом: Центр; } li {margin: 10px; } #buy {fourene: url (<c: url value = '/images/all.png'/>) без повторения; дисплей: встроенный блок; Фоно -позиция: 0 -902PX; Мяботая маржа: 30px; Высота: 36px; Ширина: 146px; } #buy: Hover {founale: url (<c: url value = '/images/all.png'/>) no-repeat; дисплей: встроенный блок; Фоно -позиция: 0 -938PX; Мяботая маржа: 30px; Высота: 36px; Ширина: 146px; } </style> </head> <body> <h1> корзина для покупок </h1> <c: выберите> <%-если нет автомобиля, или сборы контента автомобиля равен 0-длина-%> <c: Когда тест = "$ {пустые sessionscope.cart или fn: длина (сеансы value = '/images/cart.png' //// "/> </c: when> <c: иная> <таблица сотока =" 0 "founal =" black "> <tr> <td colspan =" 7 "align =" right "style =" font-size: 15pt; CART </a> </td> </tr> <tr> <th> Picture </th> <Th> Название книги </th> <Th> Автор </th> <Th> Прайс </th> <Th> Количество </th> <Th> subtotal </th> <Th> </th> </tr> <c: foreach items = "$ {sesesscope.cart.cart.cart. <tr> <td> <div> <img src = "<c: url value = '/$ {cartitem.book.image}' //"/> </div> </td> <td> $ {cartitem.book.bname} </td> <td> $ {cartitem.book. Yuan </td> <td> $ {cartitem.count} </td> <td> $ {cartitem.subtotal} yuan </td> <td> <a href = "<c: url value = '/cartservlet? </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: в противном случае> </c: выберите> </body> </html> Общедоступный класс CartServlet Extens BaseServlet { /** * Добавить заявку на покупку * @param запрос * @param response * @return * @Throws ServletException * @Throws ioException * /public String Add (httpservletrequest, httpservletresponse response) throus nevletexcept вход в машину*//** 1. Получить машину*/ cart cart = (cart) request.getSession (). getattribute ("cart"); /** Форма передает только ставку и количество* 2. Получите запись*> Получите книгу и количество*> сначала получите ставку книги, и затем нам нужно запросить базу данных через ставку, чтобы получить книгу*> Существует*/ String bid = request.getParameter ("bid"); Book Book = new Bookservice (). Load (Bid); int count = integer.parseint (request.getParameter ("count")); Cartitem cartitem = new Cartitem (); cartitem.setbook (книга); cartitem.setCount (count); /** 3. Добавить запись в машину*/ cart.add (cartitem); вернуть "f: /jsps/cart/list.jsp"; } / ** * Очистить запись в покупке * @param запрос * @param response * @return * @throws servletexception * @throws ioexception * / public String clear (httpservletrequest, httpservletrespons (Cart) request.getsession (). Getattribute ("cart"); cart.clear (); вернуть "f: /jsps/cart/list.jsp"; } / ** * Удалить записи покупок * @param запрос * @param response * @return * @throhs servletexception * @throws ioexception * / public String delete (httpservletrequest, httpservletrespons (Cart) request.getsession (). Getattribute ("cart"); String bid = request.getParameter ("bid"); cart.delete (bid); вернуть "f: /jsps/cart/list.jsp"; }}3. Очистить запись
4. Удалить вход в корзину покупок
5. Моя корзина для покупок
В Top.jsp есть ссылка: моя корзина для покупок
Моя корзина обращается напрямую/jsps/cart/list.jsp и отображает все записи тележки в сессии.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.