JavaWeb開發購物車設計總結

一. 實體類設計

圖書實體類javascript

 1 public class Book {
 2     
 3     private String id;
 4     private String name;
 5     private String author;
 6     private double price;
 7     private String description;
 8     
 9     // 省略getter setter
10 }

購物項實體類html

 1 public class CartItem {
 2 
 3     private Book book;
 4     private int quantity;
 5     private double price;
 6 
 7     /**
 8      * 重構getPrice方法
 9      * @return 購物項總價格
10      */
11     public double getPrice() {
12         return book.getPrice() * this.quantity;
13     }
14     public Book getBook() {
15         return book;
16     }
17     public void setBook(Book book) {
18         this.book = book;
19     }
20     public int getQuantity() {
21         return quantity;
22     }
23     public void setQuantity(int quantity) {
24         this.quantity = quantity;
25     }
26     public void setPrice(double price) {
27         this.price = price;
28     }
29 }

購物車實體類java

 1 public class Cart {
 2 
 3     private Map<String, CartItem> map = new LinkedHashMap();
 4     private double price;
 5 
 6     /**
 7      * 向購物車中添加圖書
 8      * @param book
 9      */
10     public void add(Book book) {
11 
12         CartItem item = map.get(book.getId());
13 
14         if(item == null) {
15             // 若不存在相同類型書籍,則建立新的購物項
16             item = new CartItem();
17             item.setBook(book);
18             item.setQuantity(1);
19             // 將購物項添加到購物車中
20             map.put(book.getId(), item);
21         } else {
22             // 若存在相同類型書籍,則將購物項個數加一
23             item.setQuantity(item.getQuantity()+1);
24         }
25     }
26     /**
27      * 重構getPrice方法
28      * @return
29      */
30     public double getPrice() {
31 
32         // 購物車總價格
33         double totalprice = 0;
34         // 迭代購物車中全部購物項, 相加獲取購物車總價
35         for(Map.Entry<String, CartItem> me : map.entrySet()) {
36             CartItem item = me.getValue();
37             totalprice += item.getPrice();
38         }
39         return totalprice;
40     }
41     public Map<String, CartItem> getMap() {
42         return map;
43     }
44     public void setMap(Map<String, CartItem> map) {
45         this.map = map;
46     }
47     public void setPrice(double price) {
48         this.price = price;
49     }
50 }

二. 業務層設計

操做購物車實際上就是操做cart對象中的map集合web

購物車四個主要功能: 數據庫

1. 添加商品到購物車session

2. 刪除購物車商品jsp

3. 清空購物車this

4. 修改購物車中購物項數量spa

 1 public class CartService {
 2     
 3     BookDao bdao = new BookDao();
 4     
 5     /**
 6      * 將圖書添加到購物車中
 7      * @param bookid
 8      * @param cart
 9      */
10     public void buybook(String bookid, Cart cart) {
11         // 根據bookid獲取圖書對象
12         Book book = bdao.find(bookid);
13         cart.add(book);
14     }
15 
16     /**
17      * 刪除購物車中指定bookid的圖書
18      * @param bookid
19      * @param cart
20      * @throws CartNotFoundException
21      */
22     public void deleteBook(String bookid, Cart cart) throws CartNotFoundException {
23 
24         //若是用戶直接訪問DeleteServlet,那麼當運行到這裏時,由於cart對象爲空,
25         //程序會拋出空指針異常。因此這裏應該判斷購物車是否爲空。
26         if(cart == null) {
27             throw new CartNotFoundException("查找不到購物車!!!");
28         }
29 
30         //String,CartItem
31         Map map = cart.getMap();
32         //刪除key爲bookid的購物項
33         map.remove(bookid);
34     }
35 
36     /**
37      * 清空購物車中全部購物項
38      * @param cart
39      * @throws CartNotFoundException
40      */
41     public void clearcart(Cart cart) throws CartNotFoundException {
42 
43         if(cart == null) {
44             throw new CartNotFoundException("查找不到購物車!!!");
45         }
46 
47         cart.getMap().clear();
48     }
49 
50     /**
51      * 更新購物項數量
52      * @param cart
53      * @param bookid
54      * @param quantity
55      * @throws CartNotFoundException
56      */
57     public void updateCart(Cart cart, String bookid, int quantity) throws CartNotFoundException {
58 
59         if(cart == null) {
60             throw new CartNotFoundException("查找不到購物車!!!");
61         }
62 
63         CartItem item = cart.getMap().get(bookid);
64         item.setQuantity(quantity);
65     }
66 }

注意: 獲取到web層傳遞過來的cart對象時, 記得檢查NPE設計

三. web層設計

1. 添加商品到購物車

 1 public class CartAddServlet extends HttpServlet {
 2     public void doGet(HttpServletRequest request, HttpServletResponse response)
 3             throws ServletException, IOException {
 4         try {
 5             String bookid = request.getParameter("bookid");
 6             // 從session中獲取購物車
 7             Cart cart = (Cart) request.getSession().getAttribute("cart");
 8             if (cart == null) {
 9                 //用戶第一次添加商品時
10                 cart = new Cart();
11                 request.getSession().setAttribute("cart", cart);
12             }
13             CartService cartService = new CartService();
14             cartService.buybook(bookid, cart);
15             request.getRequestDispatcher("/listcart.jsp").forward(request, response);
16             return;
17         } catch (Exception e) {
18             request.setAttribute("message", "操做失敗!");
19             request.getRequestDispatcher("/message.jsp").forward(request, response);
20             return;
21         }
22     }
23 }

2. 刪除購物車商品

 1 public class CartDeleteServlet extends HttpServlet {
 2     public void doGet(HttpServletRequest request, HttpServletResponse response)
 3             throws ServletException, IOException {
 4         try {
 5             String bookid = request.getParameter("bookid");
 6             Cart cart = (Cart) request.getSession().getAttribute("cart");
 7             // 獲取業務層, 刪除目標購物項
 8             CartService cartService = new CartService();
 9             cartService.deleteBook(bookid, cart);
10             // 刷新頁面
11             request.getRequestDispatcher("/listcart.jsp").forward(request, response);
12         } catch (CartNotFoundException e) {
13             request.setAttribute("message", "操做出錯!");
14             request.getRequestDispatcher("/message.jsp").forward(request, response);
15         }
16     }
17 }

3. 清空購物車

 1 public class ClearCartServlet extends HttpServlet {
 2     public void doGet(HttpServletRequest request, HttpServletResponse response)
 3             throws ServletException, IOException {
 4         try {
 5             Cart cart = (Cart) request.getSession().getAttribute("cart");
 6             CartService cartService = new CartService();
 7             cartService.clearcart(cart);
 8             request.getRequestDispatcher("/listcart.jsp").forward(request, response);
 9         } catch (CartNotFoundException e) {
10             request.setAttribute("message", "操做出錯!!");
11             request.getRequestDispatcher("/message.jsp").forward(request, response);
12         }
13     }
14 }

4. 修改購物車中購物項數量

 1 public class UpdateCartServlet extends HttpServlet {
 2     public void doGet(HttpServletRequest request, HttpServletResponse response)
 3             throws ServletException, IOException {
 4         try {
 5             //獲取操做的圖書對象
 6             String bookid = request.getParameter("bookid");
 7             //獲取改變的數量
 8             int quantity = Integer.parseInt(request.getParameter("quantity"));
 9             //獲取購物車
10             Cart cart = (Cart) request.getSession().getAttribute("cart");
11             CartService cartService = new CartService();
12             cartService.updateCart(cart, bookid, quantity);
13             request.getRequestDispatcher("/listcart.jsp").forward(request, response);
14         } catch (Exception e) {
15             request.setAttribute("message", "操做出錯!");
16             request.getRequestDispatcher("/message.jsp").forward(request, response);
17         }
18     }
19 }

5. 獲取全部商品

 1 public class ListBookServlet extends HttpServlet {
 2     public void doGet(HttpServletRequest request, HttpServletResponse response)
 3             throws ServletException, IOException {
 4         try {
 5             BookService bookService = new BookService();
 6             Map map = bookService.getAllBook();
 7             request.setAttribute("map", map);
 8             request.getRequestDispatcher("/listbook.jsp").forward(request, response);
 9             return;
10         } catch (Exception e) {
11             request.setAttribute("message", "請求失敗!");
12             request.getRequestDispatcher("/message.jsp").forward(request, response);
13             return;
14         }
15     }
16 }

四. 前臺頁面設計

listbook.jsp  獲取全部商品

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 3 
 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 5 <html>
 6   <head>
 7     <title>My JSP 'listbook.jsp' starting page</title>
 8   </head>
 9   <body>
10     <table border="1px" cellspacing="0" align="center">
11         <tr>
12             <td>圖書ID</td>
13             <td>圖書名稱</td>
14             <td>圖書做者</td>
15             <td>圖書價格</td>
16             <td>圖書描述</td>
17             <td>操做</td>
18         </tr>
19            <c:forEach var="me" items="${map }">
20             <tr>
21                 <td>${me.key }</td>
22                 <td>${me.value.name }</td>
23                 <td>${me.value.author }</td>
24                 <td>${me.value.price }</td>
25                 <td>${me.value.description }</td>
26                 <td>
27                     <a href="${pageContext.request.contextPath }/servlet/BuyServlet?bookid=${me.key }">購買</a>
28                 </td>
29                </tr>
30            </c:forEach>
31     </table>
32   </body>
33 </html>

listcart.jsp  查看購物車頁面

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 3 
 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 5 <html>
 6   <head>
 7     <title>My JSP 'listcart.jsp' starting page</title>
 8     <script type="text/javascript">
 9         //刪除商品
10         function clearcartitem(bookid) {
11             var result = window.confirm("您肯定要刪除該商品麼?");
12             if(result) {
13                 window.location.href = "${pageContext.request.contextPath }/servlet/DeleteServlet?bookid="+bookid;
14             }
15         }
16         //清空購物車
17         function clearcart() {
18             var result = window.confirm("您肯定要清空購物車麼?");
19             if(result) {
20                 window.location.href = "${pageContext.request.contextPath }/servlet/ClearCartServlet";
21             }
22         }
23         //改變購物項數量
24         function updateCart(input,id,oldvalue) {
25             var quantity = input.value;
26             //驗證非零的正整數:^\+?[1-9][0-9]*$ 
27             var reg= /^\+?[1-9][0-9]*$/;
28             var result = window.confirm("請確認改成:" + quantity);
29             //判斷輸入是否爲正整數
30             if(!reg.test(quantity)) {
31                 alert("參數不合法!");
32                 input.value = oldvalue;
33                 return;
34             }
35             
36             if(result) {
37                 window.location.href="${pageContext.request.contextPath}/servlet/UpdateCartServlet?bookid="+id + "&quantity=" + quantity;
38             } else {
39                 input.value = oldvalue;
40             }
41         }
42     </script>        
43   </head>
44   
45   <body>
46       <c:if test="${!empty(cart.map) }">
47     <table border="1px" cellspacing="0" align="center">
48         <tr>
49             <td>圖書名稱</td>
50             <td>圖書做者</td>
51             <td>單價</td>
52             <td>數量</td>
53             <td>小計</td>
54             <td>操做</td>
55         </tr>
56            <c:forEach var="me" items="${cart.map }">
57             <tr>
58                 <td>${me.value.book.name }</td>
59                 <td>${me.value.book.author }</td>
60                 <td>${me.value.book.price }</td>
61                 <td>
62                     <input type="text" name="quantity" value="${me.value.quantity }" style="width: 30px" onchange="updateCart(this,${me.value.book.id },${me.value.quantity })">
63                 </td>
64                 <td>${me.value.price }</td>
65                 <td>
66                     <a href="javascript:clearcartitem(${me.value.book.id })">刪除</a>
67                 </td>
68                </tr>
69            </c:forEach>
70            <tr>
71             <td colspan="2">
72                 <a href="javascript:clearcart()">清空購物車</a>
73             </td>
74             <td colspan="2">合計</td>
75             <td colspan="2">${cart.price }</td>
76         </tr>
77     </table>
78     </c:if>
79     
80     <c:if test="${empty(cart.map) }">
81         對不起,您尚未購買任何商品!
82     </c:if>
83   </body>
84 </html>

附: 數據庫表

create database cart_cheatsheep;

use cart_cheatsheep;

create table t_book(
    id varchar(40) primary key,
    name varchar(100) not null unique,
    author varchar(100) not null unique,
    price double not null,
    description varchar(255)
);
相關文章
相關標籤/搜索