java web開辟之完成購物車功效。本站提示廣大學習愛好者:(java web開辟之完成購物車功效)文章只能為提供參考,不一定能成為您想要的結果。以下是java web開辟之完成購物車功效正文
為了便利本身今後溫習,所以寫的比擬細心,記載下本身的生長。
既然是做購物車,那末條件前提是起首須要一系列商品,也就是要建一個實體,這裡建了一個商品表、
經由過程查詢在閱讀器上顯示
根本顯示曾經做好了,如今進入我們的重頭戲,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");
}
}
履行成果:
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。