网上图书商城项目学习笔记-013 添加购物车及我的购物车

一、流程分析

1.购物车模块

2.我的购物车分析

3.添加条目到购物车

二、代码

1.view层

(1)top.jsp

1 <a href="<c:url value='/CartItemServlet?method=myCart'/>" target="body">我的购物车</a>

(2)desc.jsp

1             <form id="form1" action="<c:url value='/CartItemServlet'/>" method="post">
2                 <input type="hidden" name="method" value="add"/>
3                 <input type="hidden" name="bid" value="${book.bid }"/>
4                   我要买:<input id="cnt" style=" 40px;text-align: center;" type="text" name="quantity" value="1"/>5               </form>

(3)list.jsp

 1 <c:choose>
 2     <c:when test="${items eq null }">
 3     <table width="95%" align="center" cellpadding="0" cellspacing="0">
 4         <tr>
 5             <td align="right">
 6                 <img align="top" src="<c:url value='/images/icon_empty.png'/>"/>
 7             </td>
 8             <td>
 9                 <span class="spanEmpty">您的购物车中暂时没有商品</span>
10             </td>
11         </tr>
12     </table>  
13 
14 <br/>
15 </c:when>
16 <c:otherwise>
17 <br/>
18 
19 
20 <table width="95%" align="center" cellpadding="0" cellspacing="0">
21     <tr align="center" bgcolor="#efeae5">
22         <td align="left" width="50px">
23             <input type="checkbox" id="selectAll" checked="checked"/><label for="selectAll">全选</label>
24         </td>
25         <td colspan="2">商品名称</td>
26         <td>单价</td>
27         <td>数量</td>
28         <td>小计</td>
29         <td>操作</td>
30     </tr>
31 
32 
33 <c:forEach items="${items }" var="item">
34 
35     <tr align="center">
36         <td align="left">
37             <input value="12345" type="checkbox" name="checkboxBtn" checked="checked"/>
38         </td>
39         <td align="left" width="70px">
40             <a class="linkImage" href="<c:url value='/jsps/book/desc.jsp'/>"><img border="0" width="54" align="top" src="<c:url value='${item.book.image_b }'/>"/></a>
41         </td>
42         <td align="left" width="400px">
43             <a href="<c:url value='/jsps/book/desc.jsp'/>"><span>${item.book.bname }</span></a>
44         </td>
45         <td><span>&yen;<span class="currPrice" id="12345CurrPrice">${item.book.currPrice }</span></span></td>
46         <td>
47             <a class="jian" id="12345Jian"></a><input class="quantity" readonly="readonly" id="12345Quantity" type="text" value="${item.quantity }"/><a class="jia" id="12345Jia"></a>
48         </td>
49         <td width="100px">
50             <span class="price_n">&yen;<span class="subTotal" id="12345Subtotal">${item.getSubTotal() }</span></span>
51         </td>
52         <td>
53             <a href="<c:url value='/jsps/cart/list.jsp'/>">删除</a>
54         </td>
55     </tr>
56 </c:forEach>
57     
58     <tr>
59         <td colspan="4" class="tdBatchDelete">
60             <a href="javascript:alert('批量删除成功');">批量删除</a>
61         </td>
62         <td colspan="3" align="right" class="tdTotal">
63             <span>总计:</span><span class="price_t">&yen;<span id="total"></span></span>
64         </td>
65     </tr>
66     <tr>
67         <td colspan="7" align="right">
68             <a href="<c:url value='/jsps/cart/showitem.jsp'/>" id="jiesuan" class="jiesuan"></a>
69         </td>
70     </tr>
71 </table>
72     <form id="form1" action="<c:url value='/jsps/cart/showitem.jsp'/>" method="post">
73         <input type="hidden" name="cartItemIds" id="cartItemIds"/>
74         <input type="hidden" name="method" value="loadCartItems"/>
75     </form>
76 </c:otherwise>    
77 </c:choose>

 

2.servlet层

(1)CartItemServlet.java

 1 public class CartItemServlet extends BaseServlet {
 2     private CartItemService service = new CartItemService();
 3     
 4     /**
 5      * 添加购物车条目
 6      * @param req
 7      * @param resp
 8      * @return
 9      * @throws ServletException
10      * @throws IOException
11      */
12     public String add(HttpServletRequest req, HttpServletResponse resp)
13             throws ServletException, IOException {
14         Map map = req.getParameterMap();
15         CartItem item = CommonUtils.toBean(map, CartItem.class);
16         Book book = CommonUtils.toBean(map, Book.class);
17         User user = (User) req.getSession().getAttribute("sessionUser");
18         item.setBook(book);
19         item.setUser(user);
20         service.add(item);
21         return myCart(req, resp);
22     }
23 
24     /**
25      * 我的购物车
26      * @param req
27      * @param resp
28      * @return
29      */
30     public String myCart(HttpServletRequest req, HttpServletResponse resp) {
31         // 1. 得到uid
32         User user = (User)req.getSession().getAttribute("sessionUser");
33         String uid = user.getUid();
34         
35         // 2. 通过service得到当前用户的所有购物车条目
36         List<CartItem> items = service.myCart(uid);
37         
38         // 3. 保存起来,转发到/cart/list.jsp
39         req.setAttribute("items", items);
40         return "f:/jsps/cart/list.jsp";
41     }
42 }

3.service层

(1)CartItemService.java

 1 public class CartItemService {
 2 
 3     private CartItemDao dao = new CartItemDao();
 4     
 5     /**
 6      * 添加条目
 7      * @param item
 8      */
 9     public void add(CartItem item) {
10         try {
11             // 1. 使用uid和bid去数据库中查询这个条目是否存在
12             CartItem _item = dao.findByUidAndBid(item.getUser().getUid(), item.getBook().getBid());
13             if(_item == null){//如果原来没有这个条目,那么添加条目
14                 item.setCartItemId(CommonUtils.uuid());
15                 dao.add(item);
16             }else{//如果原来有这个条目,修改数量
17                 // 使用原有数量和新条目数量之各,来做为新的数量
18                 _item.setQuantity(_item.getQuantity() + item.getQuantity());
19                 // 修改这个老条目的数量
20                 dao.updateQuantity(_item);
21             }
22             
23         } catch (SQLException e) {
24             throw new RuntimeException(e);
25         }
26     }
27     
28     /**
29      * 我的购物车功能
30      * @param uid
31      * @return
32      */
33     public List<CartItem> myCart(String uid) {
34         try {
35             return dao.findByUser(uid);
36         } catch (SQLException e) {
37             throw new RuntimeException(e);
38         }
39     }
40 }

4.dao层

(1)CartItem.java

 1 public class CartItemDao {
 2     private QueryRunner qr = new TxQueryRunner();
 3     
 4     /**
 5      * 添加条目
 6      * @param item
 7      * @throws SQLException
 8      */
 9     public void add(CartItem item) throws SQLException {
10         String sql = "insert into t_cartitem(cartItemId, quantity, bid, uid) values (?,?,?,?)";
11         Object [] params = {item.getCartItemId(), item.getQuantity(), item.getBook().getBid(), item.getUser().getUid()};
12         qr.update(sql, params);
13     }
14     
15     /**
16      * 通过用户查询购物车条目
17      * @param uid
18      * @return
19      * @throws SQLException
20      */
21     public List<CartItem> findByUser(String uid) throws SQLException {
22         String sql = "select * from t_cartitem c,t_book b where uid=? and c.bid=b.bid";
23         List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), uid);
24         return toCartItemList(mapList);
25     }
26 
27     
28     /**
29      * 把多个Map(List<Map>)映射成多个CartItem(List<CartItem>)
30      * @param mapList
31      * @return
32      */
33     private List<CartItem> toCartItemList(List<Map<String, Object>> mapList) {
34         List<CartItem> items = new ArrayList<CartItem>();
35         CartItem item = null;
36         for(Map<String, Object> map : mapList) {
37             item = toCartItem(map);
38             items.add(item);
39         }
40         item = null;
41         return items;
42     }
43 
44     /**
45      * 把一个Map映射成一个Cartitem
46      * @param map
47      * @return
48      */
49     private CartItem toCartItem(Map<String, Object> map) {
50         if(map == null || map.size() == 0) return null;
51         CartItem item = CommonUtils.toBean(map, CartItem.class);
52         User user = CommonUtils.toBean(map, User.class);
53         Book book = CommonUtils.toBean(map, Book.class);
54         item.setUser(user);
55         item.setBook(book);
56         return item;
57     }
58 
59     /**
60      * 查询某个用户的某本图书的购物车条目是否存在
61      * @param uid
62      * @param bid
63      * @return
64      * @throws SQLException
65      */
66     public CartItem findByUidAndBid(String uid, String bid) throws SQLException {
67         String sql= "SELECT * FROM t_cartitem c, t_user u, t_book b WHERE c.uid=u.uid AND c.bid=b.bid AND c.uid=? AND c.bid=?";
68         Map<String,Object> map = qr.query(sql, new MapHandler(), uid, bid);
69         return toCartItem(map);
70     }
71 
72     /**
73      * 修改指定条目的数量
74      * @param _item
75      * @throws SQLException
76      */
77     public void updateQuantity(CartItem _item) throws SQLException {
78         String sql = "update t_cartitem set quantity=? where cartItemId=?";
79         qr.update(sql, _item.getQuantity(), _item.getCartItemId());
80     }
81 }
原文地址:https://www.cnblogs.com/shamgod/p/5165811.html