為了方便自己以后復(fù)習(xí),所以寫(xiě)的比較仔細(xì),記錄下自己的成長(zhǎng)。
既然是做購(gòu)物車,那么前提條件是首先需要一系列商品,也就是要建一個(gè)實(shí)體,這里建了一個(gè)商品表
通過(guò)查詢?cè)跒g覽器上顯示
基本顯示已經(jīng)做好了,現(xiàn)在進(jìn)入我們的重頭戲,Servlet
點(diǎn)擊放入購(gòu)物車時(shí),將訪問(wèn)Servlet
購(gòu)物車代碼
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
|
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dao.GoodsDAO; import com.entity.Goods; import com.entity.GoodsItem; public class PutCarServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); //得到編號(hào) String id = request.getParameter( "goodsID" ); //通過(guò)編號(hào)得到商品對(duì)象的所有信息 GoodsDAO dao = new GoodsDAO(); Goods g = dao.getGoodsByID(id); //將商品放入購(gòu)物車 //map集合 就是購(gòu)物車 // map<鍵,值> 商品編號(hào)作為鍵 商品項(xiàng)作為值 //1.判斷是否存在購(gòu)物車 //購(gòu)物車是放在session中的 //從session去取購(gòu)物車 Map<String,GoodsItem> gwc = (Map<String,GoodsItem>)request.getSession().getAttribute( "gwc" ); //判斷是否存在 if (gwc== null ){ //創(chuàng)建購(gòu)物車 gwc = new HashMap<String, GoodsItem>(); } //將商品項(xiàng)放入購(gòu)物車 //put(商品編號(hào),商品項(xiàng)) 向gwc集合中添加數(shù)據(jù) //你要想 購(gòu)物車中是否已存在該商品 // 說(shuō)白了 就是在gwc集合中去匹配是否存在這樣一個(gè)商品項(xiàng) ==》去集合中匹配是否存在這樣一個(gè)商品編號(hào)的key //判斷是否存在商品編號(hào)的鍵 if (gwc.containsKey(id)){ //存在 //設(shè)置數(shù)量+1 //通過(guò)鍵 獲得值 //鍵為商品編號(hào) 值為商品項(xiàng) 商品項(xiàng)里面包含商品對(duì)象信息 和數(shù)量信息 GoodsItem spx = gwc.get(id); //得到原來(lái)的數(shù)量 int yldsl = spx.getCount(); //在原來(lái)的數(shù)量上+1 gwc.get(id).setCount(yldsl+ 1 ); // gwc.get(id).setCount(gwc.get(id).getCount()+1) ; } else { //不存在 //創(chuàng)建一個(gè)新的商品項(xiàng) 數(shù)量為1 GoodsItem gi = new GoodsItem(g, 1 ); //將此商品項(xiàng)放入gwc gwc.put(id, gi); } //將購(gòu)物車放入session request.getSession().setAttribute( "gwc" , gwc); //繼續(xù)購(gòu)物 response.sendRedirect( "index.jsp" ); } } |
執(zhí)行結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。