mvc架構實現商品的購買(二)
在上篇文章中 使用了mode1的模型來實現商品的瀏覽,這篇文章在上篇的基礎上,使用mvc架構實現商品的購買。
運行結果:
相對與上篇文章 我們多了購物車類
由于我們在購買物品時,購物車需要的屬性為購買的商品和數量 所以我們用map的鍵值來保存購買的商品。
當然還有一個總價格,購物車的方法有 添加商品 刪除商品 計算總價格 其中總價格應該在每次添加商品和刪除商品時 重新計算 購物車商品集合 只在初始化購物車的時候實例化一次即可
package entity; import java.util.HashMap; public class Cart { //購物車商品集合 private HashMap<Items,Integer> cart; //總金額 private double totalPrices; public Cart() { cart=new HashMap<Items, Integer>(); totalPrices=0.0; } public HashMap<Items, Integer> getCart() { return cart; } public void setCart(HashMap<Items, Integer> cart) { this.cart = cart; } public double getTotalPrices() { return totalPrices; } public void setTotalPrices(double totalPrices) { this.totalPrices = totalPrices; } //添加物品進購物車 public boolean addToCart(Items item,int counts){ //如果當前物品 已經添加過 只增加數量 if(cart.containsKey(item)){ cart.put(item, cart.get(item)+counts); }else{ cart.put(item, counts); } //重新計算價格 calTotalPrice(item.getPrice()*counts); return true; } //將物品從購物車刪除 public boolean removeFromCart(Items item){ if(cart!=null&&cart.containsKey(item)){ calTotalPrice(-item.getPrice()*cart.get(item)); cart.remove(item); } return true; } //計算總金額 private void calTotalPrice(double price){ totalPrices+=price; } }
CartServlet的doGett方法根據action來進行相應的處理
if (request.getParameter("action") != null) { action = request.getParameter("action"); if ("add".equals(action)) { // 添加商品 if (addGoodsToCart(request, response)) { request.getRequestDispatcher("../success.jsp").forward( request, response); } else { request.getRequestDispatcher("../failure.jsp").forward( request, response); } } else if ("show".equals(action)) {// 顯示購物車 request.getRequestDispatcher("../cart.jsp").forward(request, response); } else if ("delete".equals(action)) {// 刪除物品 deleteGoodFromCart(request, response); request.getRequestDispatcher("../cart.jsp").forward(request, response); } }
當在商品界面 我們點擊了放入購物車時 將當前商品的編號傳到 購物車的servlet類CartServlet開始處理當前物品 并將當前物品放入購物車
再放入購物車之前 首先判斷是否是第一次創(chuàng)建購物車 (購物車肯定只有一個 不能有多個)如果是第一次創(chuàng)建購物車cart
將當前購物車放入session ,然后通過ItemsDao對象調用getItemById(id)方法 獲得商品對象 。然后將相應的商品對象 和商品數量放入購物車
//向購物車添加商品 private boolean addGoodsToCart(HttpServletRequest request, HttpServletResponse response) { String id=request.getParameter("id"); String counts=request.getParameter("num"); Items item=dao.getItemById(Integer.parseInt(id)); //判斷是否是第一次創(chuàng)建購物車 if(request.getSession().getAttribute("cart")==null){ Cart cart=new Cart(); request.getSession().setAttribute("cart", cart); request.getSession().setAttribute("dao", dao); } Cart cart=(Cart) request.getSession().getAttribute("cart"); //將商品添加到購物車 if(cart.addToCart(item, Integer.parseInt(counts))){ return true; }else{ return false; } }
如果點擊了查看購物車 CartServlet重定向到購物車頁面
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%> <%@ page import="entity.Cart" %> <%@ page import="entity.Items" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cart.jsp' starting page</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"> --> <link type="text/css" rel="stylesheet" href="css/style1.css" /> <script language="javascript"> function delcfm() { if (!confirm("確認要刪除?")) { window.event.returnValue = false; } } </script> </head> <body> <h1>我的購物車</h1> <a href="goods.jsp">首頁</a> >> <a href="goods.jsp">商品列表</a> <hr> <div id="shopping"> <form action="" method=""> <table> <tr> <th>商品名稱</th> <th>商品單價</th> <th>商品價格</th> <th>購買數量</th> <th>操作</th> </tr> <% //首先判斷session中是否有購物車對象 if(request.getSession().getAttribute("cart")!=null) { %> <!-- 循環(huán)的開始 --> <% Cart cart = (Cart)request.getSession().getAttribute("cart"); HashMap<Items,Integer> goods = cart.getCart(); Set<Items> items = goods.keySet(); Iterator<Items> it = items.iterator(); while(it.hasNext()) { Items i = it.next(); %> <tr name="products" id="product_id_1"> <td class="thumb"><img src="images/<%=i.getPicture()%>" /><a href=""><%=i.getName()%></a></td> <td class="number"><%=i.getPrice() %></td> <td class="price" id="price_id_1"> <span><%=i.getPrice()*goods.get(i) %></span> <input type="hidden" value="" /> </td> <td class="number"> <%=goods.get(i)%> </td> <td class="delete"> <a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">刪除</a> </td> </tr> <% } %> <!--循環(huán)的結束--> </table> <div class="total"><span id="total">總計:<%=cart.getTotalPrices() %>¥</span></div> <% } %> <div class="button"><input type="submit" value="" /></div> </form> </div> </body> </html>
當點擊了刪除商品 CartServlet類調用刪除商品的方法
// 從購物車刪除商品 private boolean deleteGoodFromCart(HttpServletRequest request, HttpServletResponse response) { //從session中獲取購物車對象 Cart cart = (Cart) request.getSession().getAttribute("cart"); if (cart != null) { int id = Integer.parseInt(request.getParameter("id")); if (cart.removeFromCart(dao.getItemById(id))) { return true; } } return false; }
邏輯代碼主要如上。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解SpringBoot中自定義starter的開發(fā)與使用
starter是SpringBoot中非常重要的一個機制,他是基于約定優(yōu)于配置的思想所衍生出來的,本文主要介紹了SpringBoot中自定義starter的開發(fā)與使用,感興趣的可以了解下2023-09-09Spring中BeanFactory和ApplicationContext的作用和區(qū)別(推薦)
這篇文章主要介紹了Spring中BeanFactory和ApplicationContext的作用和區(qū)別,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Spring Cloud Feign實現文件上傳下載的示例代碼
Feign框架對于文件上傳消息體格式并沒有做原生支持,需要集成模塊feign-form來實現,本文就詳細的介紹一下如何使用,感興趣的可以了解一下2022-02-02Spring MVC溫故而知新系列教程之請求映射RequestMapping注解
這篇文章主要介紹了Spring MVC溫故而知新系列教程之請求映射RequestMapping注解的相關知識,文中給大家介紹了RequestMapping注解提供的幾個屬性及注解說明,感興趣的朋友跟隨腳本之家小編一起學習吧2018-05-05