我們設計購物車就是一個 Map<Product,Integer>集合,這個Map集合要存儲到session中。
一、將商品添加到購物車
1.先在頁面上添加一個鏈接
2.在AddProductToCartServlet中
1.先得到商品的id
2.從數據庫中通過id將商品查詢出來。
3.將商品添加到購物車
a.從session中獲取購物車,沒有的話,重新new 出一個
b.判斷商品在購物車中是否存在,如果不存在,數量為1,如果存在,數量在原基礎上加1
c.將購物車重新裝入到session中。
問題:我們的購物使用的是一個HashMap集合,key是唯一的,保證key唯一的方式是通過hashCode與equals方法
所以我們在使用時,需要將Product類的hashCode與equals方法重寫。
我們在重寫時,只比較id值就可以。
重寫代碼:
public class Product implements Serializable { // id VARCHAR(50) PRIMARY KEY, // NAME VARCHAR(30), // price DOUBLE, // COUNT INT, // category VARCHAR(20), // description VARCHAR(200) private String id; private String name; private double price; private int count; private String category; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Product [id=" + id + ", name=" + name + ", price=" + price + ", count=" + count + ", category=" + category + ", description=" + description + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Product other = (Product) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
二、顯示購物車商品
我們的購物車是存在於session中的。我們只需要在cart.jsp頁面將session中的cartt這個Map集合得到,並顯示出來就可以。
1. 對購物車中商品操作
在點擊+或-號時可以修改購物車中商品的數量
當點擊+或-按鈕時,我們會調用一個javascript中的函數。changeCount();通過這個函數我們向服務器發送請求,在服務器端從session中獲取購物車中數據,並根據提交的數據將購物車中指定的商品數量修改在返回到購物車頁面展示。
Js代碼
服務器端代碼
jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>shop</title> <link rel="stylesheet" href="css/main.css" type="text/css" /> <script type="text/javascript"> //當點擊+或-號時,會向服務器發送請求,並通知服務器修改哪個商品及數量是多少 function changeCount(id, count, totalCount) { //將字符串轉換成數字 count = parseInt(count); totalCount = parseInt(totalCount); //確認刪除功能 if (count <= 0) { var flag = window.confirm("確認刪除嗎"); if (!flag) { //取消時,直接讓程序結束 document.getElementById(id).value = 1; count = 1; } else { count = 0; } } //控制購買數量不能大於庫存 if (count > totalCount) { alert("最大購買數量為" + totalCount); document.getElementById(id).value = totalCount; count = totalCount; //return; } location.href = "${pageContext.request.contextPath}/changeCartCount?id=" + id + "&count=" + count; } </script> </head> <body class="main"> <div id="divpagecontent"> <table width="100%" border="0" cellspacing="0"> <tr> <td><div style="text-align:right; margin:5px 10px 5px 0px"> <a href="index.html">首頁</a> > 購物車 </div> <table cellspacing="0" class="infocontent"> <tr> <td><img src="ad/page_ad.jpg" width="666" height="89" /> <table width="100%" border="0" cellspacing="0"> <tr> <td><img src="images/buy1.gif" width="635" height="38" /> </td> </tr> <tr> <td> <table cellspacing="1" class="carttable"> <tr> <td width="25%">序號</td> <td width="15%">商品名稱</td> <td width="10%">價格</td> <td width="20%"> 數量</td> <td width="10%">庫存</td> <td width="10%">小計</td> <td width="10%">取消</td> </tr> </table> <c:forEach items="${cart}" var="entry"> <table width="100%" border="0" cellspacing="0"> <tr> <td width="25%">${entry.key.id}</td> <td width="15%">${entry.key.name}</td> <td width="10%">${entry.key.price }</td> <td width="20%"><input type="button" value='-' style="width:20px" onclick="changeCount('${entry.key.id}','${entry.value-1}','${entry.key.count}')"> <input name="text" type="text" value="${entry.value}" id="${entry.key.id}" style="width:40px;text-align:center" onblur="changeCount('${entry.key.id}',this.value,'${entry.key.count}')" /> <input type="button" value='+' style="width:20px" onclick="changeCount('${entry.key.id}','${entry.value+1}','${entry.key.count}')"> </td> <td width="10%">${entry.key.count }</td> <td width="10%">${entry.key.price*entry.value}</td> <td width="10%"><a href="javascript:void(0);" style="color:#FF0000; font-weight:bold" onclick="changeCount('${entry.key.id}','0','${entry.key.count}')">X</a> </td> </tr> </table> </c:forEach> <table cellspacing="1" class="carttable"> <tr> <td style="text-align:right; padding-right:40px;"><font style="color:#FF6600; font-weight:bold">合計: 元</font> </td> </tr> </table> <div style="text-align:right; margin-top:10px"> <a href="${pageContext.request.contextPath}/listProductByPage"><img src="images/gwc_jx.gif" border="0" /> </a> <a href="#"><img src="images/gwc_buy.gif" border="0" /> </a> </div></td> </tr> </table></td> </tr> </table> </td> </tr> </table> </div> <jsp:include page="foot.jsp" /> </body> </html>
servlet
public class AddProductToCartServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); // 1.得到id String id = request.getParameter("id"); // 2.調用service中的根據id查詢商品的方法 ProductService service = new ProductService(); try { Product p = service.findProductById(id); // 3.將商品添加到購物車 // 3.1 從session中獲取購物車 Map<Product, Integer> cart = (Map<Product, Integer>) request .getSession().getAttribute("cart"); int count = 1; // 默認數據是1 if (cart == null) { // 代表第一次購物,還沒有購物車 cart = new HashMap<Product, Integer>(); } else { // 有購物車,需要考慮在購物車中有這個商品 Integer c = cart.get(p); if (c != null) { // 說明購物車中有這個商品了 count = c + 1; } } cart.put(p, count); // 將商品添加到了購物車. // 4.將購物車存儲到session中。 request.getSession().setAttribute("cart", cart); response.getWriter() .write("<a href='" + request.getContextPath() + "/listProductByPage'>繼續購物</a>,<a href='" + request.getContextPath() + "/cart.jsp'>查看購物車</a>"); } catch (SQLException e) { e.printStackTrace(); } } }
service
public class ProductService { ProductDao dao = new ProductDao(); // 添加商品 public void addProduct(Product p) throws ProductException { try { dao.addProduct(p); } catch (SQLException e) { e.printStackTrace(); throw new ProductException("添加商品失敗"); } } // 查詢所有商品 public List<Product> findAll() throws SQLException { return dao.findAll(); } // 根據id查詢商品 public Product findProductById(String id) throws SQLException { return dao.findProductById(id); } // 修改商品 public void editProduct(Product p) throws SQLException { dao.editProduct(p); } // 刪除選中 public void delSelectById(String[] ids) throws SQLException { dao.delSelectById(ids); } public List<Product> findByCondition(String id, String category, String name, String minPrice, String maxPrice) throws SQLException { return dao.findByCondition(id, category, name, minPrice, maxPrice); } // 分頁顯示數據 // currentCount 每頁條數 // currentPage 當前頁 public PageBean findByPage(int currentCount, int currentPage) throws SQLException { // 1.求出總條數 int totalCount = dao.findAllCount(); // 2.求出總頁數 int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount); // 3.求出當前頁的數據 List<Product> ps = dao.findByPage(currentCount, currentPage); PageBean bean = new PageBean(); bean.setTotalCount(totalCount); bean.setTotalPage(totalPage); bean.setCurrentCount(currentCount); bean.setCurrentPage(currentPage); bean.setPs(ps); return bean; } }