JavaWeb开发购物车设计总结

一. 实体类设计

图书实体类

 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 }

购物项实体类

 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 }

购物车实体类

 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集合

购物车四个主要功能: 

1. 添加商品到购物车

2. 删除购物车商品

3. 清空购物车

4. 修改购物车中购物项数量

 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)
);

 

posted on 2018-09-06 20:00  ert999  阅读(15143)  评论(2编辑  收藏  举报

导航