本文實(shí)例為大家分享了購物車模塊的具體代碼,供大家參考,具體內(nèi)容如下
使用的不是session,也不是cookie,而是表
> 添加購物條目
> 修改購物條目的數(shù)量
> 刪除條目
> 批量刪除條目
> 我的購物車,即按用戶查詢條目
> 查詢勾選的條目
1.數(shù)據(jù)表
2.CartItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
public class CartItem { private String cartItemId; // 主鍵 private int quantity; // 數(shù)量 private Book book; // 條目對(duì)應(yīng)的圖書 private User user; // 所屬用戶 // 添加小計(jì)方法 public double getSubtotal() { /* * 使用BigDecimal不會(huì)有誤差 * 要求必須使用String類型構(gòu)造器 */ BigDecimal b1 = new BigDecimal(book.getCurrPrice() + "" ); BigDecimal b2 = new BigDecimal(quantity + "" ); BigDecimal b3 = b1.multiply(b2); return b3.doubleValue(); } public String getCartItemId() { return cartItemId; } public void setCartItemId(String cartItemId) { this .cartItemId = cartItemId; } public int getQuantity() { return quantity; } public void setQuantity( int quantity) { this .quantity = quantity; } public Book getBook() { return book; } public void setBook(Book book) { this .book = book; } public User getUser() { return user; } public void setUser(User user) { this .user = user; } } |
小技巧:Java中四舍五入 BigDecimal不會(huì)有誤差
1
2
3
4
5
6
7
8
9
10
11
12
|
// 添加小計(jì)方法 public double getSubtotal() { /* * 使用BigDecimal不會(huì)有誤差 * 要求必須使用String類型構(gòu)造器 */ BigDecimal b1 = new BigDecimal(book.getCurrPrice() + "" ); BigDecimal b2 = new BigDecimal(quantity + "" ); BigDecimal b3 = b1.multiply(b2); return b3.doubleValue(); } |
3.通過用戶查詢購物車條目
我的購物車條目中每個(gè)條目需要顯示圖書的圖片 書名 單價(jià) ,這說明需要多表查詢
1
2
3
4
5
|
public List<CartItem> findByUser(String uid) throws SQLException { String sql = "select * from t_cartitem c, t_book b where c.bid=b.bid and uid=? order by c.orderBy" ; List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler(), uid); return toCartItemList(mapList); } |
4.添加購物車條目----增
jsp
1
2
3
4
5
6
7
8
|
< div class = "divForm" > < form id = "form1" action="<c:url value = '/CartItemServlet' />" method="post"> < input type = "hidden" name = "method" value = "add" /> < input type = "hidden" name = "bid" value = "${book.bid }" /> 我要買:< input id = "cnt" style = "width: 40px;text-align: center;" type = "text" name = "quantity" value = "1" />件 </ form > < a id = "btn" href = "javascript:$('#form1').submit();" ></ a > </ div > |
CartItemServlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* * 1. 封裝表單數(shù)據(jù)到CartItem(bid, quantity) */ Map map = req.getParameterMap(); CartItem cartItem = CommonUtils.toBean(map, CartItem. class ); Book book = CommonUtils.toBean(map, Book. class ); User user = (User)req.getSession().getAttribute( "sessionUser" ); cartItem.setBook(book); cartItem.setUser(user); cartItemService.add(cartItem); return myCart(req, resp); } |
CartItemService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public void add(CartItem cartItem) { try { /* * 1. 使用uid和bid去數(shù)據(jù)庫中查詢這個(gè)條目是否存在 */ CartItem _cartItem = cartItemDao.findByUidAndBid( cartItem.getUser().getUid(), cartItem.getBook().getBid()); if (_cartItem == null ) { //如果原來沒有這個(gè)條目,那么添加條目 cartItem.setCartItemId(CommonUtils.uuid()); cartItemDao.addCartItem(cartItem); } else { //如果原來有這個(gè)條目,修改數(shù)量 // 使用原有數(shù)量和新條目數(shù)量之各,來做為新的數(shù)量 int quantity = cartItem.getQuantity() + _cartItem.getQuantity(); // 修改這個(gè)老條目的數(shù)量 cartItemDao.updateQuantity(_cartItem.getCartItemId(), quantity); } } catch (Exception e) { throw new RuntimeException(e); } } |
CartItemDao
1
2
3
4
5
6
7
|
public void addCartItem(CartItem cartItem) throws SQLException { String sql = "insert into t_cartitem(cartItemId, quantity, bid, uid)" + " values(?,?,?,?)" ; Object[] params = {cartItem.getCartItemId(), cartItem.getQuantity(), cartItem.getBook().getBid(), cartItem.getUser().getUid()}; qr.update(sql, params); } |
5.購物車模塊頁面javascript----查
計(jì)算總計(jì)
給全選添加click事件
給所有條目的復(fù)選框添加click事件
給減號(hào)添加click事件
給加號(hào)添加click事件
批量刪除
list.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
|
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> < html > < head > < title >cartlist.jsp</ title > < meta http-equiv = "pragma" content = "no-cache" > < meta http-equiv = "cache-control" content = "no-cache" > < meta http-equiv = "expires" content = "0" > < meta http-equiv = "keywords" content = "keyword1,keyword2,keyword3" > < meta http-equiv = "description" content = "This is my page" > <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> < script src="<c:url value = '/jquery/jquery-1.5.1.js' />"></ script > < script src="<c:url value = '/js/round.js' />"></ script > < link rel = "stylesheet" type = "text/css" href="<c:url value = '/jsps/css/cart/list.css' />"> < script type = "text/javascript" > $(function() { showTotal();//計(jì)算總計(jì) /* 給全選添加click事件 */ $("#selectAll").click(function() { /* 1. 獲取全選的狀態(tài) */ var bool = $("#selectAll").attr("checked"); /* 2. 讓所有條目的復(fù)選框與全選的狀態(tài)同步 */ setItemCheckBox(bool); /* 3. 讓結(jié)算按鈕與全選同步 */ setJieSuan(bool); /* 4. 重新計(jì)算總計(jì) */ showTotal(); }); /* 給所有條目的復(fù)選框添加click事件 */ $(":checkbox[name=checkboxBtn]").click(function() { var all = $(":checkbox[name=checkboxBtn]").length;//所有條目的個(gè)數(shù) var select = $(":checkbox[name=checkboxBtn][checked=true]").length;//獲取所有被選擇條目的個(gè)數(shù) if(all == select) {//全都選中了 $("#selectAll").attr("checked", true);//勾選全選復(fù)選框 setJieSuan(true);//讓結(jié)算按鈕有效 } else if(select == 0) {//誰都沒有選中 $("#selectAll").attr("checked", false);//取消全選 setJieSuan(false);//讓結(jié)算失效 } else { $("#selectAll").attr("checked", false);//取消全選 setJieSuan(true);//讓結(jié)算有效 } showTotal();//重新計(jì)算總計(jì) }); /* 給減號(hào)添加click事件 */ $(".jian").click(function() { // 獲取cartItemId var id = $(this).attr("id").substring(0, 32); // 獲取輸入框中的數(shù)量 var quantity = $("#" + id + "Quantity").val(); // 判斷當(dāng)前數(shù)量是否為1,如果為1,那就不是修改數(shù)量了,而是要?jiǎng)h除了。 if(quantity == 1) { if(confirm("您是否真要?jiǎng)h除該條目?")) { location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + id; } } else { sendUpdateQuantity(id, quantity-1); } }); // 給加號(hào)添加click事件 $(".jia").click(function() { // 獲取cartItemId var id = $(this).attr("id").substring(0, 32); // 獲取輸入框中的數(shù)量 var quantity = $("#" + id + "Quantity").val(); sendUpdateQuantity(id, Number(quantity)+1); }); }); // 請(qǐng)求服務(wù)器,修改數(shù)量。 function sendUpdateQuantity(id, quantity) { $.ajax({ async:false, cache:false, url:"/goods/CartItemServlet", data:{method:"updateQuantity",cartItemId:id,quantity:quantity}, type:"POST", dataType:"json", success:function(result) { //1. 修改數(shù)量 $("#" + id + "Quantity").val(result.quantity); //2. 修改小計(jì) $("#" + id + "Subtotal").text(result.subtotal); //3. 重新計(jì)算總計(jì) showTotal(); } }); } /* * 計(jì)算總計(jì) */ function showTotal() { var total = 0; /* 1. 獲取所有的被勾選的條目復(fù)選框!循環(huán)遍歷之 */ $(":checkbox[name=checkboxBtn][checked=true]").each(function() { //2. 獲取復(fù)選框的值,即其他元素的前綴 var id = $(this).val(); //3. 再通過前綴找到小計(jì)元素,獲取其文本 var text = $("#" + id + "Subtotal").text(); //4. 累加計(jì)算 total += Number(text); }); // 5. 把總計(jì)顯示在總計(jì)元素上 $("#total").text(round(total, 2));//round()函數(shù)的作用是把total保留2位 } /* * 統(tǒng)一設(shè)置所有條目的復(fù)選按鈕 */ function setItemCheckBox(bool) { $(":checkbox[name=checkboxBtn]").attr("checked", bool); } /* * 設(shè)置結(jié)算按鈕樣式 */ function setJieSuan(bool) { if(bool) { $("#jiesuan").removeClass("kill").addClass("jiesuan"); $("#jiesuan").unbind("click");//撤消當(dāng)前元素止所有click事件 } else { $("#jiesuan").removeClass("jiesuan").addClass("kill"); $("#jiesuan").click(function() {return false;}); } } /* * 批量刪除 */ function batchDelete() { // 1. 獲取所有被選中條目的復(fù)選框 // 2. 創(chuàng)建一數(shù)組,把所有被選中的復(fù)選框的值添加到數(shù)組中 // 3. 指定location為CartItemServlet,參數(shù)method=batchDelete,參數(shù)cartItemIds=數(shù)組的toString() var cartItemIdArray = new Array(); $(":checkbox[name=checkboxBtn][checked=true]").each(function() { cartItemIdArray.push($(this).val());//把復(fù)選框的值添加到數(shù)組中 }); location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + cartItemIdArray; } /* * 結(jié)算 */ function jiesuan() { // 1. 獲取所有被選擇的條目的id,放到數(shù)組中 var cartItemIdArray = new Array(); $(":checkbox[name=checkboxBtn][checked=true]").each(function() { cartItemIdArray.push($(this).val());//把復(fù)選框的值添加到數(shù)組中 }); // 2. 把數(shù)組的值toString(),然后賦給表單的cartItemIds這個(gè)hidden $("#cartItemIds").val(cartItemIdArray.toString()); // 把總計(jì)的值,也保存到表單中 $("#hiddenTotal").val($("#total").text()); // 3. 提交這個(gè)表單 $("#jieSuanForm").submit(); } </ script > </ head > < body > < c:choose > < c:when test = "${empty cartItemList }" > < table width = "95%" align = "center" cellpadding = "0" cellspacing = "0" > < tr > < td align = "right" > < img align = "top" src="<c:url value = '/images/icon_empty.png' />"/> </ td > < td > < span class = "spanEmpty" >您的購物車中暫時(shí)沒有商品</ span > </ td > </ tr > </ table > </ c:when > < c:otherwise > < table width = "95%" align = "center" cellpadding = "0" cellspacing = "0" > < tr align = "center" bgcolor = "#efeae5" > < td align = "left" width = "50px" > < input type = "checkbox" id = "selectAll" checked = "checked" />< label for = "selectAll" >全選</ label > </ td > < td colspan = "2" >商品名稱</ td > < td >單價(jià)</ td > < td >數(shù)量</ td > < td >小計(jì)</ td > < td >操作</ td > </ tr > < c:forEach items = "${cartItemList }" var = "cartItem" > < tr align = "center" > < td align = "left" > < input value = "${cartItem.cartItemId }" type = "checkbox" name = "checkboxBtn" checked = "checked" /> </ td > < td align = "left" width = "70px" > < a class = "linkImage" href="<c:url value = '/jsps/book/desc.jsp' />">< img border = "0" width = "54" align = "top" src="<c:url value = '/${cartItem.book.image_b }' />"/></ a > </ td > < td align = "left" width = "400px" > < a href="<c:url value = '/jsps/book/desc.jsp' />">< span >${cartItem.book.bname }</ span ></ a > </ td > < td >< span >¥< span class = "currPrice" >${cartItem.book.currPrice }</ span ></ span ></ td > < td > < a class = "jian" id = "${cartItem.cartItemId }Jian" ></ a >< input class = "quantity" readonly = "readonly" id = "${cartItem.cartItemId }Quantity" type = "text" value = "${cartItem.quantity }" />< a class = "jia" id = "${cartItem.cartItemId }Jia" ></ a > </ td > < td width = "100px" > < span class = "price_n" >¥< span class = "subTotal" id = "${cartItem.cartItemId }Subtotal" >${cartItem.subtotal }</ span ></ span > </ td > < td > < a href="<c:url value = '/CartItemServlet?method=batchDelete&cartItemIds=${cartItem.cartItemId }' />">刪除</ a > </ td > </ tr > </ c:forEach > < tr > < td colspan = "4" class = "tdBatchDelete" > < a href = "javascript:batchDelete();" >批量刪除</ a > </ td > < td colspan = "3" align = "right" class = "tdTotal" > < span >總計(jì):</ span >< span class = "price_t" >¥< span id = "total" ></ span ></ span > </ td > </ tr > < tr > < td colspan = "7" align = "right" > < a href = "javascript:jiesuan();" id = "jiesuan" class = "jiesuan" ></ a > </ td > </ tr > </ table > < form id = "jieSuanForm" action="<c:url value = '/CartItemServlet' />" method="post"> < input type = "hidden" name = "cartItemIds" id = "cartItemIds" /> < input type = "hidden" name = "total" id = "hiddenTotal" /> < input type = "hidden" name = "method" value = "loadCartItems" /> </ form > </ c:otherwise > </ c:choose > </ body > </ html > |
小技巧:js中四舍五入round.js
1
2
|
// 5. 把總計(jì)顯示在總計(jì)元素上 $( "#total" ).text(round(total, 2)); //round()函數(shù)的作用是把total保留2位 |
6.批量刪除功能----刪
jsp
1
2
3
4
5
6
7
8
9
10
|
function batchDelete() { // 1. 獲取所有被選中條目的復(fù)選框 // 2. 創(chuàng)建一數(shù)組,把所有被選中的復(fù)選框的值添加到數(shù)組中 // 3. 指定location為CartItemServlet,參數(shù)method=batchDelete,參數(shù)cartItemIds=數(shù)組的toString() var cartItemIdArray = new Array(); $( ":checkbox[name=checkboxBtn][checked=true]" ).each( function () { cartItemIdArray.push($( this ).val()); //把復(fù)選框的值添加到數(shù)組中 }); location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + cartItemIdArray; } |
刪除一個(gè)
1
2
3
4
5
6
|
if (quantity == 1) { if (confirm( "您是否真要?jiǎng)h除該條目?" )) { location = "/goods/CartItemServlet?method=batchDelete&cartItemIds=" + id; } } else { |
7.修改數(shù)量----改
jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 請(qǐng)求服務(wù)器,修改數(shù)量。 function sendUpdateQuantity(id, quantity) { $.ajax({ async: false , cache: false , url: "/goods/CartItemServlet" , data:{method: "updateQuantity" ,cartItemId:id,quantity:quantity}, type: "POST" , dataType: "json" , success:function(result) { //1. 修改數(shù)量 $( "#" + id + "Quantity" ).val(result.quantity); //2. 修改小計(jì) $( "#" + id + "Subtotal" ).text(result.subtotal); //3. 重新計(jì)算總計(jì) showTotal(); } }); } |
servlet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public String updateQuantity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cartItemId = req.getParameter( "cartItemId" ); int quantity = Integer.parseInt(req.getParameter( "quantity" )); CartItem cartItem = cartItemService.updateQuantity(cartItemId, quantity); // 給客戶端返回一個(gè)json對(duì)象 StringBuilder sb = new StringBuilder( "{" ); sb.append( "\"quantity\"" ).append( ":" ).append(cartItem.getQuantity()); sb.append( "," ); sb.append( "\"subtotal\"" ).append( ":" ).append(cartItem.getSubtotal()); sb.append( "}" ); resp.getWriter().print(sb); return null ; } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。