日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
淺談實現(xiàn)基于Javabean與JSP的購物車功能

首先呢,在買了東西之后要放在購物車?yán)?,?dāng)車子里的物品有相同時就疊加,不再創(chuàng)建物品對象,有了物品之后肯 定要有價格,數(shù)量等等對象。這些對象我們要封裝在JAVABEAN 中的!有了Javabean就需要建立SERVLET來進(jìn)行與業(yè)務(wù)層連接,我們就需要有,增加購物車,刪除購物車,清楚購物車等一系列的Servlet和SERVICE層連接!SERVICE層調(diào)用DAO層,這些步驟正體現(xiàn)出了MVC的設(shè)計模式!下面我們看具體的實現(xiàn)基于Javabean與JSP的購物車功能吧!

(1) 1. 代表購物車的ShoppingCart 類

 
 
 
  1. public class ShoppingCart {  
  2.  //裝載 ShoppingCartItem 的數(shù)據(jù)結(jié)構(gòu): Map, 鍵: 書的 id, 值: 書對應(yīng)的 ShoppingCartItem  
  3.  private Map, ShoppingCartItem> books = null;  
  4.    
  5.  public ShoppingCart(){  
  6.   books = new HashMap, ShoppingCartItem>();  
  7.  }   
  8.  
  9.  public Map, ShoppingCartItem> getBooks() {  
  10.   return books;  
  11.  }  
  12.    
  13.  public Book getBook(String bookId){  
  14.   Book book = null;  
  15.     
  16.   ShoppingCartItem sci = this.books.get(bookId);  
  17.   if (sci == null)  
  18.    return null;  
  19.     
  20.   return sci.getBook ();  
  21.  }  
  22.    
  23.  public float getTotalPrice(){  
  24.   float totalPrice = 0.0f;  
  25.     
  26.   //對 books 中的 value 進(jìn)行遍歷, 取其 price 屬性的和   
  27.   Iterator iterator = books.values().iterator ();  
  28.   while(iterator.hasNext()){  
  29.    ShoppingCartItem sci = iterator.next();  
  30.    totalPrice += sci.getPrice();  
  31.   }   
  32.     
  33.   return totalPrice;  
  34.  }  
  35.    
  36.  public int getTotalQuantity(){  
  37.   int quantity = 0;  
  38.     
  39.   //對 books 中的 value 進(jìn)行遍歷, 取其 quantity 屬性的和  
  40.   Iterator iterator = books.values().iterator();  
  41.   while(iterator.hasNext()) {  
  42.    ShoppingCartItem sci = iterator.next();  
  43.    quantity += sci.getQuantity();  
  44.   }  
  45.     
  46.   return quantity;  
  47.  }   
  48.    
  49.  public boolean isExistInShoppingCart(String bookId){  
  50.   return this.books.get(bookId) != null;  
  51.  }  
  52.    
  53.  public ShoppingCartItem getShoppingCartItemByBookId(String bookId){  
  54.   return this.books.get(bookId);  
  55.  }   
  56.    
  57.  public void addNewItemToShoppingCart(ShoppingCartItem sci) {  
  58.   this.books.put(sci.getBook().getId(), sci);  
  59.  }  

2. 代表購物車中的物品

 
 
 
  1. public class ShoppingCartItem {  
  2.  //具體指向某本書  
  3.  private Book book;  
  4.    
  5.  //當(dāng)前商品在購物車中的數(shù)量  
  6.  private int quantity;  
  7.    
  8.  public ShoppingCartItem(Book book) {  
  9.   this.book = book;  
  10.   this.quantity = 1;  
  11.  }  
  12.  
  13.  //當(dāng)前商品的總價格  
  14.  private float price;  
  15.    
  16.  public void incrementQuantity(){  
  17.   this.quantity++;  
  18.  }  
  19.  
  20.  public Book getBook() {  
  21.   return book;  
  22.  }  
  23.  
  24.  public void setBook(Book book) {  
  25.   this.book = book;  
  26.  }  
  27.  
  28.  public int getQuantity() {  
  29.   return quantity;  
  30.  }  
  31.  
  32.  public void setQuantity(int quantity) {  
  33.   this.quantity = quantity;  
  34.  }   
  35.  
  36.  public float getPrice() {  
  37.   return this.book.getPrice() * this.quantity;  
  38.  }  
  39.  

(2)建立DAO,此時有人會問,這次DAO為什么沒有購物車呢,因為購物車是沒有數(shù)據(jù)的,而是里面的物品才有 數(shù)據(jù)的,當(dāng)有更新購物車?yán)锩娴奈锲窌r才會早DAO里面寫方法!

 
 
 
  1. public class BookDAO {  
  2.    
  3.  //  
  4.  public void upadateBookQuantityByBookId(Connection conn, String bookId, int quantity){  
  5.   String sql = "UPDATE books SET saleAmount = saleAmount + ? WHERE id = ?";  
  6.   Object [] params = new Object[]{quantity, bookId};  
  7.     
  8.   QueryRunner queryRunner = new QueryRunner ();  
  9.     
  10.   try {  
  11.    queryRunner.update(conn, sql, params);  
  12.   } catch (SQLException e) {  
  13.    // TODO Auto-generated catch block  
  14.    e.printStackTrace();  
  15.    throw new RuntimeException (MyBookStoreConstants.UPDATE_BOOK_SALEAMOUNT_BY_BOOK_ID_EXCEPTION);  
  16.   }  
  17.  } 

(3) 建立業(yè)務(wù)層,涉及到添加,清空等方法!這邊佟剛老師的代碼都有詳細(xì)的解釋!

 
 
 
  1. public class BookService {  
  2.  //根據(jù)給定的 ShoppingCart 對象, 調(diào)用 DAO 方法進(jìn)行數(shù)據(jù)庫更新操作  
  3.  public void buyBooks(ShoppingCart sc){  
  4.   //對 sc 中的 ShoppingCartItem 對象進(jìn)行遍歷, 調(diào)用 BookDAO.upadateBookQuantityByBookId 方法  
  5.   Connection conn = null;  
  6.   conn = DBHelper.getConnection();  
  7.     
  8.   try {  
  9.    Iterator shoppingCartItemSet = sc.getBooks().values ().iterator();  
  10.    BookDAO bookDAO = new BookDAO ();  
  11.      
  12.    while(shoppingCartItemSet.hasNext()) {  
  13.     ShoppingCartItem sci = shoppingCartItemSet.next ();  
  14.       
  15.     String bookId = sci.getBook().getId ();  
  16.     int quantity = sci.getQuantity ();  
  17.       
  18.     bookDAO.upadateBookQuantityByBookId(conn, bookId, quantity);  
  19.    }  
  20.   }finally {  
  21.    DBHelper.releaseDBSource(null, null, conn);  
  22.   }   
  23.     
  24.     
  25.  }  
  26.    
  27.  //參數(shù) items 中的鍵為 書的 id 號, 值為購 物車中對應(yīng)的 數(shù)量  
  28.  public void updateShoppingCart(Map,Integer> items, ShoppingCart sc){  
  29.   Set keySet = null;  
  30.   keySet = items.keySet ();  
  31.     
  32.   for(Iterator it = keySet.iterator(); it.hasNext(); ) {  
  33.    String bookId = it.next();  
  34.    int quantity = items.get (bookId);  
  35.      
  36.    if(quantity <= 0) {  
  37.     sc.getBooks().remove(bookId);  
  38.    }else {  
  39.     sc.getShoppingCartItemByBookId(bookId).setQuantity (quantity);  
  40.    }  
  41.       
  42.   }  
  43.  }   
  44.    
  45.  //清空購物車  
  46.  public void clearShoppingCart(ShoppingCart sc) {  
  47.   sc.getBooks().clear();  
  48.  }  
  49.    
  50.  public void deleteShoppingCartItemById(String id, ShoppingCart sc){  
  51.   //刪除 sc 中的 id 元素   
  52.   sc.getBooks().remove(id);  
  53.  }  
  54.    
  55.  //把 id 對應(yīng)的 ShoppingCartItem 對象放入購物車 ShoppingCart 對象中  
  56.  public void addToShoppingCart(String id, ShoppingCart sc) {  
  57.     
  58.   //1. 查看 sc 中有沒有 id 對應(yīng)的 ShoppingCartItem 對象   
  59.   if(sc.isExistInShoppingCart(id)){  
  60.    //1.1 有: 把該對象取出, 使其數(shù)量 + 1, 調(diào)用 sci.increseQuantity(); 方法  
  61.    ShoppingCartItem scsci = sc.getShoppingCartItemByBookId(id);  
  62.    sci.incrementQuantity();  
  63.   }   
  64.   //1.2 沒有: 創(chuàng)建一個新的 ShoppingCartItem 對象, 并將其放入 sc 中, 以書的 id 作為鍵   
  65.   else{  
  66.    //1.2.1 根據(jù) id 獲取相應(yīng)的 Book 對象, 調(diào)用 BookDAO 的 selectBookByBookId() 方法  
  67.    Book book = null;  
  68.    BookDAO bookDAO = null;  
  69.      
  70.    bookDAO = new BookDAO();  
  71.    book = bookDAO.selectBookByBookId(id);  
  72.      
  73.    ShoppingCartItem sci = null;  
  74.    sci = new ShoppingCartItem (book);  
  75.      
  76.    sc.addNewItemToShoppingCart(sci);  
  77.   }   
  78.  }  

(4)這段是 檢查購物車是有對象的,這里單獨拿出來是可以很好的在WEB開發(fā)中很好的進(jìn)行重用 的。

 
 
 
  1. public class MyBookStoreUtils {  
  2.  private MyBookStoreUtils(){}  
  3.    
  4.  public static  ShoppingCart getShppingCartForCreateOrExist(HttpServletRequest request) {  
  5.   ShoppingCart sc = null;  
  6.   //2.1 檢查在 HttpSession 對象中有沒有購物車對象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性  
  7.   //   若 已經(jīng)存在, 說明購物車存在, 直接取出  
  8.   HttpSession session = null;  
  9.   session = request.getSession();  
  10.     
  11.   Object obj = session.getAttribute (MyBookStoreConstants.SHOOPING_CART_KEY);  
  12.     
  13.   if(obj != null) {  
  14.    sc = (ShoppingCart) obj;  
  15.   }  
  16.   //2.2 若不存在 MyBookStoreConstants.SHOOPING_CART_KEY 屬性, 創(chuàng)建一個購物車對象, 并把該對象放入 Session 中   
  17.   else{  
  18.    sc = new ShoppingCart ();  
  19.    session.setAttribute(MyBookStoreConstants.SHOOPING_CART_KEY, sc);  
  20.   }  
  21.     
  22.   return sc;  
  23.  }  
  24.    
  25.  public static  ShoppingCart getShppingCartForExist(HttpServletRequest request) {  
  26.   ShoppingCart sc = null;  
  27.   //2.1 檢查在 HttpSession 對象中有沒有購物車對象 , 即檢查 session 中是否有 MyBookStoreConstants.SHOOPING_CART_KEY 屬性  
  28.   //   若 已經(jīng)存在, 說明購物車存在, 直接取出  
  29.   HttpSession session = null;  
  30.   session = request.getSession();  
  31.     
  32.   Object obj = session.getAttribute (MyBookStoreConstants.SHOOPING_CART_KEY);  
  33.     
  34.   if(obj != null) {  
  35.    sc = (ShoppingCart) obj;  
  36.   }  
  37.   //2.2 若不存在 MyBookStoreConstants.SHOOPING_CART_KEY 屬性, 拋出異常, 提示用戶還不存在購物車.  
  38.   else {  
  39.    throw new RuntimeException (MyBookStoreConstants.NO_SHOPPING_CART_EXCETPION);  
  40.   }   
  41.     
  42.   return sc;  
  43.  }  

(5)這里是所有與購物車相關(guān)的SERVLET.

這個是更新數(shù)據(jù)的,需要在SERVICE中調(diào)用DAO的!

 
 
 
  1. public class UpdateShoppingCartServlet extends HttpServlet {  
  2.  
  3.  public void doPost(HttpServletRequest request, HttpServletResponse response)   
  4.    throws ServletException, IOException {  
  5.   //獲取表單信息   
  6.   // request.getParameter(""); 方法行不通, 因為表單的 name 是隨時變化的   
  7.     
  8.   //獲取表單中的所有 name  
  9.   Enumeration nameEnums = request.getParameterNames();  
  10.     
  11.   Map items = new HashMap, Integer>();  
  12.   //遍歷 nameEnums, 再取出對應(yīng)的 Value, 封裝到 items 中   
  13.     
  14.   try {  
  15.    while(nameEnums.hasMoreElements()) {  
  16.     String bookId = nameEnums.nextElement();  
  17.     String quantity = request.getParameter (bookId);  
  18.       
  19.     items.put(bookId, Integer.parseInt (quantity));  
  20.    }  
  21.   } catch (NumberFormatException e) {  
  22.    // TODO Auto-generated catch block  
  23.    e.printStackTrace ();  
  24.    throw new RuntimeException (MyBookStoreConstants.QUANTITY_FORMAT_EXCEPTION);  
  25.   }  
  26.     
  27.   //獲 取購物車對象  
  28.   ShoppingCart sc = null;  
  29.   sc = MyBookStoreUtils.getShppingCartForExist(request);  
  30.     
  31.   //調(diào)用 Service 方法   
  32.   BookService bookService = new BookService ();  
  33.   bookService.updateShoppingCart(items, sc);  
  34.     
  35.   //派發(fā)頁面 : showShoppingCart.jsp 頁面  
  36.   String forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp";  
  37.   request.getRequestDispatcher(forwardPage).forward (request, response);  
  38.  }  
  39.  
  40. }  
  41.  
  42. public class ShowShoppingCartServlet extends HttpServlet {  
  43.  
  44.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
  45.    throws ServletException, IOException {  
  46.   //做一個轉(zhuǎn)發(fā)   
  47.   String forwardPage = null;  
  48.     
  49.   forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp";  
  50.     
  51.   RequestDispatcher dispatcher = null;  
  52.   dispatcher = request.getRequestDispatcher (forwardPage);  
  53.   dispatcher.forward(request, response);  
  54.  }  
  55.  
  56. }  
  57. public class ReceiptServlet extends HttpServlet {  
  58.  
  59.  public void doPost(HttpServletRequest request, HttpServletResponse response)   
  60.    throws ServletException, IOException {  
  61.   //1. 獲取表單信息: name 和 cardId  
  62.     
  63.   //2. 調(diào)用 Service 方法, 更新 books 表各條 book 的 saleAmount 字段   
  64.     
  65.   //2.1 獲取購物車  
  66.   ShoppingCart sc = MyBookStoreUtils.getShppingCartForExist(request);  
  67.     
  68.   BookService bookService = new BookService();  
  69.   bookService.buyBooks (sc);  
  70.     
  71.   //2.1 使 Session 失效  
  72.   HttpSession session = null;  
  73.   session = request.getSession();  
  74.   session.invalidate ();  
  75.     
  76.   //3. 派發(fā)頁面: receipt.jsp 頁面   
  77.   request.getRequestDispatcher("/WEB-INF/jsp/receipt.jsp").forward(request, response);   
  78.  }  

這段我先開始很納悶老師為什么會這樣寫呢,其實很簡單,寫個專門的轉(zhuǎn)發(fā)的SERVLET這樣,在每次轉(zhuǎn)發(fā)的時候就只連接一個servlet比連接多個更來的簡潔!提高了效率!

 
 
 
  1. public class ForwardServlet extends HttpServlet {  
  2.  
  3.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
  4.    throws ServletException, IOException {  
  5.   //1. 獲取 path  
  6.   String path = request.getParameter("path");  
  7.     
  8.   //2. 派 發(fā)頁面  
  9.   request.getRequestDispatcher(path).forward(request, response);  
  10.  }  
  11.  
  12. }  
  13. public class DeleteShoppingCartItemServlet extends HttpServlet {  
  14.  
  15.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
  16.    throws ServletException, IOException {  
  17.   //1. 獲取 id 號   
  18.   String id = request.getParameter("bookid");  
  19.     
  20.   //2. 調(diào)用 BookService 方法 deleteShoppingCartItemById:, 進(jìn)行刪除操作  
  21.   ShoppingCart sc = MyBookStoreUtils.getShppingCartForExist(request);  
  22.     
  23.   String bookTitle = sc.getBook(id).getTitle();  
  24.     
  25.   BookService bookService = new BookService ();  
  26.   bookService.deleteShoppingCartItemById(id, sc);  
  27.     
  28.   //3. 派發(fā)頁面  
  29.   request.setAttribute(MyBookStoreConstants.DELETE_FROM_SHOPPING_CART_BOOK_TITLE, bookTitle);  
  30.     
  31.   String forwardPage = "/WEB- INF/jsp/showShoppingCart.jsp";  
  32.   //4. 判斷購物車是否為空, 若為空則派發(fā)到 emptyCart.jsp 頁面  
  33.   if(sc.getBooks().isEmpty())  
  34.    forwardPage = "/WEB- INF/jsp/emptyCart.jsp";  
  35.     
  36.   RequestDispatcher dispatcher = null;  
  37.   dispatcher = request.getRequestDispatcher (forwardPage);  
  38.   dispatcher.forward(request, response);  
  39.  }  
  40.  } 

這里是清空購物車的SERVLET.

 
 
 
  1. public class ClearShoppingCartServlet extends HttpServlet {  
  2.  
  3.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
  4.    throws ServletException, IOException {  
  5.   //1. 調(diào)用方法   
  6.   BookService bookService = new BookService ();  
  7.     
  8.   ShoppingCart sc = null;  
  9.   sc = MyBookStoreUtils.getShppingCartForExist (request);  
  10.     
  11.   bookService.clearShoppingCart (sc);  
  12.     
  13.   //2. 派發(fā)頁面  
  14.   String forwardPage = null;  
  15.   forwardPage = "/WEB- INF/jsp/emptyCart.jsp";  
  16.     
  17.   RequestDispatcher dispatcher = request.getRequestDispatcher(forwardPage);  
  18.   dispatcher.forward(request, response);  
  19.  }  
  20.  
  21. }  
  22. public class AddToShoppingCartServlet extends HttpServlet {  
  23.  
  24.  public void doGet(HttpServletRequest request, HttpServletResponse response)   
  25.    throws ServletException, IOException {  
  26.     
  27.     
  28.   //1. 獲取書的 id 號  
  29.   String bookId = null;  
  30.   bookId = request.getParameter("bookId");  
  31.     
  32.   //2. 獲取 購物車對象: 調(diào)用 getShppingCart 方法  
  33.   ShoppingCart sc = null;  
  34.   sc = MyBookStoreUtils.getShppingCartForCreateOrExist(request);  
  35.     
  36.   //3. 調(diào)用 Service 方法把 id 對應(yīng)的 ShoppingCartItem 對象放入購物車 ShoppingCart 對象中: addToShoppingCart(id, shoppingCart);  
  37.   BookService bookService = null;  
  38.   bookService = new BookService();  
  39.     
  40.   bookService.addToShoppingCart(bookId, sc);  
  41.     
  42.   //4. 派發(fā)頁面  
  43.   String forwardPage = "/index.jsp";  
  44.     
  45.   //4.1 獲取書名  
  46.   String bookTitle = null;  
  47.   //bookTitle = sc.getBooks().get(bookId).getBook().getTitle ();  
  48.   bookTitle = sc.getBook(bookId).getTitle();  
  49.     
  50.   //4.2 將書 名放入請求域中, 以讓頁面進(jìn)行顯示  
  51.   request.setAttribute (MyBookStoreConstants.ADD_TO_SHOPPING_CART_BOOK_TITLE, bookTitle);  
  52.     
  53.   RequestDispatcher dispatcher = null;  
  54.   dispatcher = request.getRequestDispatcher (forwardPage);  
  55.   dispatcher.forward(request, response);  
  56.  }  
  57.  

(6)下面是顯示層,對應(yīng)著其相應(yīng)的SERVLET.下面的JSP頁面運用到了我們前段時間學(xué)的JSTL,EL表示.
 'cashier.jsp'

 
 
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% > 
  2.  
  3. > 
  4.  
  5.    
  6.     </strong>My JSP 'cashier.jsp' starting page<strong> 
  7.    
  8.    
  9.    
  10.     
     
  11.      

     
  12.      您一共購買 了 ${sessionScope.shoppingcartkey.totalQuantity} 本書  
  13.      

     
  14.      您應(yīng)付金額 是:${sessionScope.shoppingcartkey.totalPrice} 元。  
  15.      

     
  16.       action="receiptServlet" method="POST"> 
  17.        
  18.        
  19.  
  20.         
  21.  
  22.         
  23.  
  24.        
  25.  
  26.        
  27.  
  28.         
  29.  
  30.         
  31.           
  32.        
  33.  
  34.         align="center"> 
  35.          colspan="2"> 
  36.           type="submit" value="遞交 "/> 
  37.          
  38.         
  39.       
  40. 信用卡用戶 名:  type="text" name="userName"/>
    信用卡帳號:  type="text" name="cardId"/>
     
  41.       
  42.      
  43.    
  44.  
  45.  'receipt.jsp'  
  46. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
  47.  
  48. > 
  49.  
  50.    
  51.     </strong>My JSP 'emptyCart.jsp' starting page<strong> 
  52.    
  53.    
  54.    
  55.     
     
  56.      

     
  57.      您的購物車 為空

     
  58.       href="${pageContext.request.contextPath }/index.jsp">繼續(xù)購物 
  59.      
  60.    
  61.  
  62. <%@ page language="java" import="java.util.*" pageEncoding="UTF- 8"%> 
  63.  
  64. > 
  65.  
  66.    
  67.     </strong>My JSP 'receipt.jsp' starting page<strong> 
  68.    
  69.    
  70.    
  71.     再見: ${param.userName }

     
  72.     href="${pageContext.request.contextPath }/index.jsp">繼續(xù)購物    
  73.    
  74.  
  75.  
  76. 'showShoppingCart.jsp'  
  77. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% > 
  78. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
  79.  
  80. > 
  81.  
  82.    
  83.     </strong>My JSP 'showShoppingCart.jsp' starting page<strong> 
  84.    
  85.    
  86.    
  87.     
     
  88.       test="${requestScope.deleteToShoppingCartBookTitle != null}"> 
  89.       

     
  90.        您已經(jīng)把 ${requestScope.deleteToShoppingCartBookTitle} 從購物車中刪除了!  
  91.       
  92.      

     
  93.        您的購物車中一共有 ${sessionScope.shoppingcartkey.totalQuantity} 本書  
  94.      

     
  95.       action="updateShoppingCartServlet" method="POST"> 
  96.        cellpadding="10" cellspacing="0"> 
  97.         
  98.         書名 
  99.         價 格 
  100.         數(shù)量  
  101.          
  102.         
  103.         items="${sessionScope.shoppingcartkey.books}"&n
    網(wǎng)頁名稱:淺談實現(xiàn)基于Javabean與JSP的購物車功能
    文章路徑:http://www.dlmjj.cn/article/dpcpsoc.html