您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“如何實(shí)現(xiàn)Javabean與JSP的購物車功能”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
首先呢,在買了東西之后要放在購物車?yán)铮?dāng)車子里的物品有相同時(shí)就疊加,不再創(chuàng)建物品對(duì)象,有了物品之后肯 定要有價(jià)格,數(shù)量等等對(duì)象。這些對(duì)象我們要封裝在JAVABEAN 中的!有了Javabean就需要建立SERVLET來進(jìn)行與業(yè)務(wù)層連接,我們就需要有,增加購物車,刪除購物車,清楚購物車等一系列的Servlet和SERVICE層連接!SERVICE層調(diào)用DAO層,這些步驟正體現(xiàn)出了MVC的設(shè)計(jì)模式!下面我們看具體的實(shí)現(xiàn)基于Javabean與JSP的購物車功能吧!
(1) 1. 代表購物車的ShoppingCart 類
public class ShoppingCart { //裝載 ShoppingCartItem 的數(shù)據(jù)結(jié)構(gòu): Map, 鍵: 書的 id, 值: 書對(duì)應(yīng)的 ShoppingCartItem private Map<String, ShoppingCartItem> books = null; public ShoppingCart(){ books = new HashMap<String, ShoppingCartItem>(); } public Map<String, ShoppingCartItem> getBooks() { return books; } public Book getBook(String bookId){ Book book = null; ShoppingCartItem sci = this.books.get(bookId); if (sci == null) return null; return sci.getBook (); } public float getTotalPrice(){ float totalPrice = 0.0f; //對(duì) books 中的 value 進(jìn)行遍歷, 取其 price 屬性的和 Iterator<ShoppingCartItem> iterator = books.values().iterator (); while(iterator.hasNext()){ ShoppingCartItem sci = iterator.next(); totalPrice += sci.getPrice(); } return totalPrice; } public int getTotalQuantity(){ int quantity = 0; //對(duì) books 中的 value 進(jìn)行遍歷, 取其 quantity 屬性的和 Iterator<ShoppingCartItem> iterator = books.values().iterator(); while(iterator.hasNext()) { ShoppingCartItem sci = iterator.next(); quantity += sci.getQuantity(); } return quantity; } public boolean isExistInShoppingCart(String bookId){ return this.books.get(bookId) != null; } public ShoppingCartItem getShoppingCartItemByBookId(String bookId){ return this.books.get(bookId); } public void addNewItemToShoppingCart(ShoppingCartItem sci) { this.books.put(sci.getBook().getId(), sci); } }
2. 代表購物車中的物品
public class ShoppingCartItem { //具體指向某本書 private Book book; //當(dāng)前商品在購物車中的數(shù)量 private int quantity; public ShoppingCartItem(Book book) { this.book = book; this.quantity = 1; } //當(dāng)前商品的總價(jià)格 private float price; public void incrementQuantity(){ this.quantity++; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public float getPrice() { return this.book.getPrice() * this.quantity; } }
(2)建立DAO,此時(shí)有人會(huì)問,這次DAO為什么沒有購物車呢,因?yàn)橘徫镘囀菦]有數(shù)據(jù)的,而是里面的物品才有 數(shù)據(jù)的,當(dāng)有更新購物車?yán)锩娴奈锲窌r(shí)才會(huì)早DAO里面寫方法!
public class BookDAO { // public void upadateBookQuantityByBookId(Connection conn, String bookId, int quantity){ String sql = "UPDATE books SET saleAmount = saleAmount + ? WHERE id = ?"; Object [] params = new Object[]{quantity, bookId}; QueryRunner queryRunner = new QueryRunner (); try { queryRunner.update(conn, sql, params); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException (MyBookStoreConstants.UPDATE_BOOK_SALEAMOUNT_BY_BOOK_ID_EXCEPTION); } }
(3) 建立業(yè)務(wù)層,涉及到添加,清空等方法!這邊佟剛老師的代碼都有詳細(xì)的解釋!
public class BookService { //根據(jù)給定的 ShoppingCart 對(duì)象, 調(diào)用 DAO 方法進(jìn)行數(shù)據(jù)庫更新操作 public void buyBooks(ShoppingCart sc){ //對(duì) sc 中的 ShoppingCartItem 對(duì)象進(jìn)行遍歷, 調(diào)用 BookDAO.upadateBookQuantityByBookId 方法 Connection conn = null; conn = DBHelper.getConnection(); try { Iterator<ShoppingCartItem> shoppingCartItemSet = sc.getBooks().values ().iterator(); BookDAO bookDAO = new BookDAO (); while(shoppingCartItemSet.hasNext()) { ShoppingCartItem sci = shoppingCartItemSet.next (); String bookId = sci.getBook().getId (); int quantity = sci.getQuantity (); bookDAO.upadateBookQuantityByBookId(conn, bookId, quantity); } }finally { DBHelper.releaseDBSource(null, null, conn); } } //參數(shù) items 中的鍵為 書的 id 號(hào), 值為購 物車中對(duì)應(yīng)的 數(shù)量 public void updateShoppingCart(Map<String,Integer> items, ShoppingCart sc){ Set<String> keySet = null; keySet = items.keySet (); for(Iterator<String> it = keySet.iterator(); it.hasNext(); ) { String bookId = it.next(); int quantity = items.get (bookId); if(quantity <= 0) { sc.getBooks().remove(bookId); }else { sc.getShoppingCartItemByBookId(bookId).setQuantity (quantity); } } } //清空購物車 public void clearShoppingCart(ShoppingCart sc) { sc.getBooks().clear(); } public void deleteShoppingCartItemById(String id, ShoppingCart sc){ //刪除 sc 中的 id 元素 sc.getBooks().remove(id); } //把 id 對(duì)應(yīng)的 ShoppingCartItem 對(duì)象放入購物車 ShoppingCart 對(duì)象中 public void addToShoppingCart(String id, ShoppingCart sc) { //1. 查看 sc 中有沒有 id 對(duì)應(yīng)的 ShoppingCartItem 對(duì)象 if(sc.isExistInShoppingCart(id)){ //1.1 有: 把該對(duì)象取出, 使其數(shù)量 + 1, 調(diào)用 sci.increseQuantity(); 方法 ShoppingCartItem scsci = sc.getShoppingCartItemByBookId(id); sci.incrementQuantity(); } //1.2 沒有: 創(chuàng)建一個(gè)新的 ShoppingCartItem 對(duì)象, 并將其放入 sc 中, 以書的 id 作為鍵 else{ //1.2.1 根據(jù) id 獲取相應(yīng)的 Book 對(duì)象, 調(diào)用 BookDAO 的 selectBookByBookId() 方法 Book book = null; BookDAO bookDAO = null; bookDAO = new BookDAO(); book = bookDAO.selectBookByBookId(id); ShoppingCartItem sci = null; sci = new ShoppingCartItem (book); sc.addNewItemToShoppingCart(sci); } } }
(4)這段是 檢查購物車是有對(duì)象的,這里單獨(dú)拿出來是可以很好的在WEB開發(fā)中很好的進(jìn)行重用 的。
public class MyBookStoreUtils { private MyBookStoreUtils(){} public static ShoppingCart getShppingCartForCreateOrExist(HttpServletRequest request) { ShoppingCart sc = null; //2.1 檢查在 HttpSession 對(duì)象中有沒有購物車對(duì)象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性 // 若 已經(jīng)存在, 說明購物車存在, 直接取出 HttpSession session = null; session = request.getSession(); Object obj = session.getAttribute (MyBookStoreConstants.SHOOPING_CART_KEY); if(obj != null) { sc = (ShoppingCart) obj; } //2.2 若不存在 MyBookStoreConstants.SHOOPING_CART_KEY 屬性, 創(chuàng)建一個(gè)購物車對(duì)象, 并把該對(duì)象放入 Session 中 else{ sc = new ShoppingCart (); session.setAttribute(MyBookStoreConstants.SHOOPING_CART_KEY, sc); } return sc; } public static ShoppingCart getShppingCartForExist(HttpServletRequest request) { ShoppingCart sc = null; //2.1 檢查在 HttpSession 對(duì)象中有沒有購物車對(duì)象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性 // 若 已經(jīng)存在, 說明購物車存在, 直接取出 HttpSession session = null; session = request.getSession(); Object obj = session.getAttribute (MyBookStoreConstants.SHOOPING_CART_KEY); if(obj != null) { sc = (ShoppingCart) obj; } //2.2 若不存在 MyBookStoreConstants.SHOOPING_CART_KEY 屬性, 拋出異常, 提示用戶還不存在購物車. else { throw new RuntimeException (MyBookStoreConstants.NO_SHOPPING_CART_EXCETPION); } return sc; } }
(5)這里是所有與購物車相關(guān)的SERVLET.
這個(gè)是更新數(shù)據(jù)的,需要在SERVICE中調(diào)用DAO的!
public class UpdateShoppingCartServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取表單信息 // request.getParameter(""); 方法行不通, 因?yàn)楸韱蔚摹ame 是隨時(shí)變化的 //獲取表單中的所有 name Enumeration<String> nameEnums = request.getParameterNames(); Map items = new HashMap<String, Integer>(); //遍歷 nameEnums, 再取出對(duì)應(yīng)的 Value, 封裝到 items 中 try { while(nameEnums.hasMoreElements()) { String bookId = nameEnums.nextElement(); String quantity = request.getParameter (bookId); items.put(bookId, Integer.parseInt (quantity)); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace (); throw new RuntimeException (MyBookStoreConstants.QUANTITY_FORMAT_EXCEPTION); } //獲 取購物車對(duì)象 ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForExist(request); //調(diào)用 Service 方法 BookService bookService = new BookService (); bookService.updateShoppingCart(items, sc); //派發(fā)頁面 : showShoppingCart.jsp 頁面 String forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp"; request.getRequestDispatcher(forwardPage).forward (request, response); } } public class ShowShoppingCartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //做一個(gè)轉(zhuǎn)發(fā) String forwardPage = null; forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp"; RequestDispatcher dispatcher = null; dispatcher = request.getRequestDispatcher (forwardPage); dispatcher.forward(request, response); } } public class ReceiptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取表單信息: name 和 cardId //2. 調(diào)用 Service 方法, 更新 books 表各條 book 的 saleAmount 字段 //2.1 獲取購物車 ShoppingCart sc = MyBookStoreUtils.getShppingCartForExist(request); BookService bookService = new BookService(); bookService.buyBooks (sc); //2.1 使 Session 失效 HttpSession session = null; session = request.getSession(); session.invalidate (); //3. 派發(fā)頁面: receipt.jsp 頁面 request.getRequestDispatcher("/WEB-INF/jsp/receipt.jsp").forward(request, response); } }
這段我先開始很納悶老師為什么會(huì)這樣寫呢,其實(shí)很簡(jiǎn)單,寫個(gè)專門的轉(zhuǎn)發(fā)的SERVLET這樣,在每次轉(zhuǎn)發(fā)的時(shí)候就只連接一個(gè)servlet比連接多個(gè)更來的簡(jiǎn)潔!提高了效率!
public class ForwardServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取 path String path = request.getParameter("path"); //2. 派 發(fā)頁面 request.getRequestDispatcher(path).forward(request, response); } } public class DeleteShoppingCartItemServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取 id 號(hào) String id = request.getParameter("bookid"); //2. 調(diào)用 BookService 方法 deleteShoppingCartItemById:, 進(jìn)行刪除操作 ShoppingCart sc = MyBookStoreUtils.getShppingCartForExist(request); String bookTitle = sc.getBook(id).getTitle(); BookService bookService = new BookService (); bookService.deleteShoppingCartItemById(id, sc); //3. 派發(fā)頁面 request.setAttribute(MyBookStoreConstants.DELETE_FROM_SHOPPING_CART_BOOK_TITLE, bookTitle); String forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp"; //4. 判斷購物車是否為空, 若為空則派發(fā)到 emptyCart.jsp 頁面 if(sc.getBooks().isEmpty()) forwardPage = "/WEB- INF/jsp/emptyCart.jsp"; RequestDispatcher dispatcher = null; dispatcher = request.getRequestDispatcher (forwardPage); dispatcher.forward(request, response); } }
這里是清空購物車的SERVLET.
public class ClearShoppingCartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 調(diào)用方法 BookService bookService = new BookService (); ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForExist (request); bookService.clearShoppingCart (sc); //2. 派發(fā)頁面 String forwardPage = null; forwardPage = "/WEB- INF/jsp/emptyCart.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(forwardPage); dispatcher.forward(request, response); } } public class AddToShoppingCartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取書的 id 號(hào) String bookId = null; bookId = request.getParameter("bookId"); //2. 獲取 購物車對(duì)象: 調(diào)用 getShppingCart 方法 ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForCreateOrExist(request); //3. 調(diào)用 Service 方法把 id 對(duì)應(yīng)的 ShoppingCartItem 對(duì)象放入購物車 ShoppingCart 對(duì)象中: addToShoppingCart(id, shoppingCart); BookService bookService = null; bookService = new BookService(); bookService.addToShoppingCart(bookId, sc); //4. 派發(fā)頁面 String forwardPage = "/index.jsp"; //4.1 獲取書名 String bookTitle = null; //bookTitle = sc.getBooks().get(bookId).getBook().getTitle (); bookTitle = sc.getBook(bookId).getTitle(); //4.2 將書 名放入請(qǐng)求域中, 以讓頁面進(jìn)行顯示 request.setAttribute (MyBookStoreConstants.ADD_TO_SHOPPING_CART_BOOK_TITLE, bookTitle); RequestDispatcher dispatcher = null; dispatcher = request.getRequestDispatcher (forwardPage); dispatcher.forward(request, response); } }
(6)下面是顯示層,對(duì)應(yīng)著其相應(yīng)的SERVLET.下面的JSP頁面運(yùn)用到了我們前段時(shí)間學(xué)的JSTL,EL表示.
'cashier.jsp'
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% > <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'cashier.jsp' starting page</title> </head> <body> <center> <br><br> 您一共購買 了 ${sessionScope.shoppingcartkey.totalQuantity} 本書 <br><br> 您應(yīng)付金額 是:${sessionScope.shoppingcartkey.totalPrice} 元。 <br><br> <form action="receiptServlet" method="POST"> <table> <tr> <td>信用卡用戶 名:</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>信用卡帳號(hào):</td> <td><input type="text" name="cardId"/></td> </tr> <tr align="center"> <td colspan="2"> <input type="submit" value="遞交 "/> </td> </tr> </table> </form> </center> </body> </html> 'receipt.jsp' <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'emptyCart.jsp' starting page</title> </head> <body> <center> <br><br> 您的購物車 為空<br><br> <a href="${pageContext.request.contextPath }/index.jsp">繼續(xù)購物<a> </center> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF- 8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'receipt.jsp' starting page</title> </head> <body> 再見: ${param.userName }<br><br> <a href="${pageContext.request.contextPath }/index.jsp">繼續(xù)購物</a> </body> </html> 'showShoppingCart.jsp' <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% > <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'showShoppingCart.jsp' starting page</title> </head> <body> <center> <c:if test="${requestScope.deleteToShoppingCartBookTitle != null}"> <br><br> 您已經(jīng)把 ${requestScope.deleteToShoppingCartBookTitle} 從購物車中刪除了! </c:if> <br><br> 您的購物車中一共有 ${sessionScope.shoppingcartkey.totalQuantity} 本書 <br><br> <form action="updateShoppingCartServlet" method="POST"> <table cellpadding="10" cellspacing="0"> <tr> <th>書名</th> <th>價(jià) 格</th> <th>數(shù)量 </th> <td></td> </tr> <c:forEach items="${sessionScope.shoppingcartkey.books}" var="sci"> <tr> <td>${sci.value.book.title }</td> <td>${sci.value.book.price }</td> <td><input type="text" value="${sci.value.quantity }" name="${sci.key }" size="2" /></td> <td><a href="${pageContext.request.contextPath }/deleteShoppingCartItemServlet?bookid=${sci.key }">刪除 </a></td> <td></td> </tr> </c:forEach> </table> <input type="submit" value="保存修 改"> </form> <br> 總價(jià)格: ${sessionScope.shoppingcartkey.totalPrice} <br><br> <a href="${pageContext.request.contextPath }/index.jsp">繼續(xù)購物 </a> <a href="${pageContext.request.contextPath }/clearShoppingCartServlet">清空購物車 </a> <a href="${pageContext.request.contextPath }/forwardServlet?path=cashier.jsp">付賬 </a> </center> </body> </html>
“如何實(shí)現(xiàn)Javabean與JSP的購物車功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。