為了方便自己以後復習,所以寫的比較仔細,記錄下自己的成長。
既然是做購物車,那麼前提條件是首先需要一系列商品,也就是要建一個實體,這裡建了一個商品表、
通過查詢在瀏覽器上顯示
基本顯示已經做好了,現在進入我們的重頭戲,Servlet
點擊放入購物車時,將訪問Servlet
購物車代碼
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(); //得到編號String id = request.getParameter("goodsID"); //通過編號得到商品對象的所有信息GoodsDAO dao = new GoodsDAO(); Goods g = dao.getGoodsByID(id); //將商品放入購物車//map集合就是購物車// map<鍵,值> 商品編號作為鍵商品項作為值//1.判斷是否存在購物車//購物車是放在session中的//從session去取購物車Map<String,GoodsItem> gwc = (Map<String,GoodsItem>)request.getSession().getAttribute("gwc"); //判斷是否存在if(gwc==null){ //創建購物車gwc = new HashMap<String, GoodsItem>(); } //將商品項放入購物車//put(商品編號,商品項) 向gwc集合中添加數據//你要想購物車中是否已存在該商品// 說白了就是在gwc集合中去匹配是否存在這樣一個商品項==》去集合中匹配是否存在這樣一個商品編號的key //判斷是否存在商品編號的鍵if(gwc.containsKey(id)){ //存在//設置數量+1 //通過鍵獲得值//鍵為商品編號值為商品項商品項裡麵包含商品對象信息和數量信息GoodsItem spx = gwc.get(id); //得到原來的數量int yldsl = spx.getCount(); //在原來的數量上+1 gwc.get(id).setCount(yldsl+1); // gwc.get(id).setCount(gwc.get(id).getCount()+1) ; }else{ //不存在//創建一個新的商品項數量為1 GoodsItem gi = new GoodsItem(g, 1); //將此商品項放入gwc gwc.put(id, gi); } //將購物車放入session request.getSession().setAttribute("gwc", gwc); //繼續購物response.sendRedirect("index.jsp"); }}執行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。