您好,登錄后才能下訂單哦!
本篇內容介紹了“如何實現Javabean與JSP的購物車功能”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
首先呢,在買了東西之后要放在購物車里,當車子里的物品有相同時就疊加,不再創建物品對象,有了物品之后肯 定要有價格,數量等等對象。這些對象我們要封裝在JAVABEAN 中的!有了Javabean就需要建立SERVLET來進行與業務層連接,我們就需要有,增加購物車,刪除購物車,清楚購物車等一系列的Servlet和SERVICE層連接!SERVICE層調用DAO層,這些步驟正體現出了MVC的設計模式!下面我們看具體的實現基于Javabean與JSP的購物車功能吧!
(1) 1. 代表購物車的ShoppingCart 類
public class ShoppingCart { //裝載 ShoppingCartItem 的數據結構: Map, 鍵: 書的 id, 值: 書對應的 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; //對 books 中的 value 進行遍歷, 取其 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; //對 books 中的 value 進行遍歷, 取其 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; //當前商品在購物車中的數量 private int quantity; public ShoppingCartItem(Book book) { this.book = book; this.quantity = 1; } //當前商品的總價格 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,此時有人會問,這次DAO為什么沒有購物車呢,因為購物車是沒有數據的,而是里面的物品才有 數據的,當有更新購物車里面的物品時才會早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) 建立業務層,涉及到添加,清空等方法!這邊佟剛老師的代碼都有詳細的解釋!
public class BookService { //根據給定的 ShoppingCart 對象, 調用 DAO 方法進行數據庫更新操作 public void buyBooks(ShoppingCart sc){ //對 sc 中的 ShoppingCartItem 對象進行遍歷, 調用 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); } } //參數 items 中的鍵為 書的 id 號, 值為購 物車中對應的 數量 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 對應的 ShoppingCartItem 對象放入購物車 ShoppingCart 對象中 public void addToShoppingCart(String id, ShoppingCart sc) { //1. 查看 sc 中有沒有 id 對應的 ShoppingCartItem 對象 if(sc.isExistInShoppingCart(id)){ //1.1 有: 把該對象取出, 使其數量 + 1, 調用 sci.increseQuantity(); 方法 ShoppingCartItem scsci = sc.getShoppingCartItemByBookId(id); sci.incrementQuantity(); } //1.2 沒有: 創建一個新的 ShoppingCartItem 對象, 并將其放入 sc 中, 以書的 id 作為鍵 else{ //1.2.1 根據 id 獲取相應的 Book 對象, 調用 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)這段是 檢查購物車是有對象的,這里單獨拿出來是可以很好的在WEB開發中很好的進行重用 的。
public class MyBookStoreUtils { private MyBookStoreUtils(){} public static ShoppingCart getShppingCartForCreateOrExist(HttpServletRequest request) { ShoppingCart sc = null; //2.1 檢查在 HttpSession 對象中有沒有購物車對象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性 // 若 已經存在, 說明購物車存在, 直接取出 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 屬性, 創建一個購物車對象, 并把該對象放入 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 對象中有沒有購物車對象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性 // 若 已經存在, 說明購物車存在, 直接取出 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)這里是所有與購物車相關的SERVLET.
這個是更新數據的,需要在SERVICE中調用DAO的!
public class UpdateShoppingCartServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取表單信息 // request.getParameter(""); 方法行不通, 因為表單的 name 是隨時變化的 //獲取表單中的所有 name Enumeration<String> nameEnums = request.getParameterNames(); Map items = new HashMap<String, Integer>(); //遍歷 nameEnums, 再取出對應的 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); } //獲 取購物車對象 ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForExist(request); //調用 Service 方法 BookService bookService = new BookService (); bookService.updateShoppingCart(items, sc); //派發頁面 : 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 { //做一個轉發 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. 調用 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. 派發頁面: receipt.jsp 頁面 request.getRequestDispatcher("/WEB-INF/jsp/receipt.jsp").forward(request, response); } }
這段我先開始很納悶老師為什么會這樣寫呢,其實很簡單,寫個專門的轉發的SERVLET這樣,在每次轉發的時候就只連接一個servlet比連接多個更來的簡潔!提高了效率!
public class ForwardServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取 path String path = request.getParameter("path"); //2. 派 發頁面 request.getRequestDispatcher(path).forward(request, response); } } public class DeleteShoppingCartItemServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 獲取 id 號 String id = request.getParameter("bookid"); //2. 調用 BookService 方法 deleteShoppingCartItemById:, 進行刪除操作 ShoppingCart sc = MyBookStoreUtils.getShppingCartForExist(request); String bookTitle = sc.getBook(id).getTitle(); BookService bookService = new BookService (); bookService.deleteShoppingCartItemById(id, sc); //3. 派發頁面 request.setAttribute(MyBookStoreConstants.DELETE_FROM_SHOPPING_CART_BOOK_TITLE, bookTitle); String forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp"; //4. 判斷購物車是否為空, 若為空則派發到 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. 調用方法 BookService bookService = new BookService (); ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForExist (request); bookService.clearShoppingCart (sc); //2. 派發頁面 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 號 String bookId = null; bookId = request.getParameter("bookId"); //2. 獲取 購物車對象: 調用 getShppingCart 方法 ShoppingCart sc = null; sc = MyBookStoreUtils.getShppingCartForCreateOrExist(request); //3. 調用 Service 方法把 id 對應的 ShoppingCartItem 對象放入購物車 ShoppingCart 對象中: addToShoppingCart(id, shoppingCart); BookService bookService = null; bookService = new BookService(); bookService.addToShoppingCart(bookId, sc); //4. 派發頁面 String forwardPage = "/index.jsp"; //4.1 獲取書名 String bookTitle = null; //bookTitle = sc.getBooks().get(bookId).getBook().getTitle (); bookTitle = sc.getBook(bookId).getTitle(); //4.2 將書 名放入請求域中, 以讓頁面進行顯示 request.setAttribute (MyBookStoreConstants.ADD_TO_SHOPPING_CART_BOOK_TITLE, bookTitle); RequestDispatcher dispatcher = null; dispatcher = request.getRequestDispatcher (forwardPage); dispatcher.forward(request, response); } }
(6)下面是顯示層,對應著其相應的SERVLET.下面的JSP頁面運用到了我們前段時間學的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> 您應付金額 是:${sessionScope.shoppingcartkey.totalPrice} 元。 <br><br> <form action="receiptServlet" method="POST"> <table> <tr> <td>信用卡用戶 名:</td> <td><input type="text" name="userName"/></td> </tr> <tr> <td>信用卡帳號:</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">繼續購物<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">繼續購物</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> 您已經把 ${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>價 格</th> <th>數量 </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> 總價格: ${sessionScope.shoppingcartkey.totalPrice} <br><br> <a href="${pageContext.request.contextPath }/index.jsp">繼續購物 </a> <a href="${pageContext.request.contextPath }/clearShoppingCartServlet">清空購物車 </a> <a href="${pageContext.request.contextPath }/forwardServlet?path=cashier.jsp">付賬 </a> </center> </body> </html>
“如何實現Javabean與JSP的購物車功能”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。