為了方便自己以後復習,所以寫的比較仔細,記錄下自己的成長。。。。。
既然是做購物車,那麼前提條件是首先需要一系列商品,也就是要建一個實體,這裡建了一個商品表、

通過查詢在浏覽器上顯示

基本顯示已經做好了,現在進入我們的重頭戲,Servlet
點擊放入購物車時,將訪問Servlet

購物車代碼
1 package com.servlet;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 import com.dao.GoodsDAO;
14 import com.entity.Goods;
15 import com.entity.GoodsItem;
16
17 public class PutCarServlet extends HttpServlet {
18
19 public void doGet(HttpServletRequest request, HttpServletResponse response)
20 throws ServletException, IOException {
21
22 response.setContentType("text/html");
23 PrintWriter out = response.getWriter();
24
25 doPost(request, response);
26 }
27
28 public void doPost(HttpServletRequest request, HttpServletResponse response)
29 throws ServletException, IOException {
30
31 response.setContentType("text/html");
32 PrintWriter out = response.getWriter();
33 //得到編號
34 String id = request.getParameter("goodsID");
35
36 //通過編號得到商品對象的所有信息
37 GoodsDAO dao = new GoodsDAO();
38 Goods g = dao.getGoodsByID(id);
39 //將商品放入購物車
40
41 //map集合 就是購物車
42 // map<鍵,值> 商品編號作為鍵 商品項作為值
43
44 //1.判斷是否存在購物車
45 //購物車是放在session中的
46 //從session去取購物車
47 Map<String,GoodsItem> gwc = (Map<String,GoodsItem>)request.getSession().getAttribute("gwc");
48 //判斷是否存在
49 if(gwc==null){
50 //創建購物車
51 gwc = new HashMap<String, GoodsItem>();
52 }
53
54 //將商品項放入購物車
55 //put(商品編號,商品項) 向gwc集合中添加數據
56 //你要想 購物車中是否已存在該商品
57 // 說白了 就是在gwc集合中去匹配是否存在這樣一個商品項 ==》去集合中匹配是否存在這樣一個商品編號的key
58
59 //判斷是否存在商品編號的鍵
60
61 if(gwc.containsKey(id)){
62 //存在
63 //設置數量+1
64
65 //通過鍵 獲得值
66 //鍵為商品編號 值為商品項 商品項裡面包含商品對象信息 和數量信息
67 GoodsItem spx = gwc.get(id);
68 //得到原來的數量
69 int yldsl = spx.getCount();
70 //在原來的數量上+1
71 gwc.get(id).setCount(yldsl+1);
72
73 // gwc.get(id).setCount(gwc.get(id).getCount()+1) ;
74
75 }else{
76 //不存在
77 //創建一個新的商品項 數量為1
78 GoodsItem gi = new GoodsItem(g, 1);
79
80 //將此商品項放入gwc
81 gwc.put(id, gi);
82 }
83
84 //將購物車放入session
85 request.getSession().setAttribute("gwc", gwc);
86
87 //繼續購物
88 response.sendRedirect("index.jsp");
89 }
90
91 }
執行結果:
