Ajax中的购物车

1.大纲设计

  

 

2.shopingCartItem.java

 1 package beans;
 2 
 3 public class shopingCartItem {
 4     private String bookname;//书对象
 5     private int num;  //书的数量
 6     private int price;  // 书的价格
 7     public int getNum() {
 8         return num;
 9     }
10     public void setNum(int num) {
11         this.num = num;
12     }
13     public String getBookname() {
14         return bookname;
15     }
16     public void setBookname(String bookname) {
17         this.bookname = bookname;
18     }
19     public int getPrice() {
20         return price;
21     }
22     public void setPrice(int price) {
23         this.price = price;
24     }
25 }

 

3.shopingCart.java

 1 package beans;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class shopingCart {
 7     //存放shopingCartItem的map,键是书名,值是shopingCartItem对象
 8     private Map<String,shopingCartItem> items=new HashMap<>();
 9     /**
10      * 将书名与书的价格添加到购物车
11      * @param bookName
12      * @param price
13      */
14     public void addToCart(String bookName,int price) {
15         if(items.containsKey(bookName)) {
16             shopingCartItem item=items.get(bookName);
17             item.setNum(item.getNum()+1);
18         }else {
19             shopingCartItem item=new shopingCartItem();
20             item.setBookname(bookName);
21             item.setPrice(price);
22             item.setNum(1);
23             items.put(bookName, item);
24         }
25     }
26     /**
27      * 返回书的总数量
28      * @return
29      */
30     public int totalBookNumer() {
31         int totalNum=0;
32         for(shopingCartItem item:items.values()) {
33             totalNum+=item.getNum();
34         }
35         return totalNum;
36     }
37     /**
38      * 返回书的总价钱
39      */
40     public int totalBookPrice() {
41         int totalPrice=0;
42         for(shopingCartItem item:items.values()) {
43             totalPrice+=item.getNum()*item.getPrice();
44         }
45         return totalPrice;
46     }
47 }

 

4.AddToCartServlet.java

 1 package servlets;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Servlet;
 6 import javax.servlet.ServletConfig;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.ServletRequest;
 9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14 
15 import beans.shopingCart;
16 
17 public class AddToCartServlet extends HttpServlet {
18 
19     private static final long serialVersionUID = 1L;
20 
21     @Override
22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23         doPost(request,response);    
24     }
25 
26     @Override
27     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
28         //获取请求参数
29         String bookName=request.getParameter("id");
30         int price=Integer.parseInt(request.getParameter("price"));
31         //获取购物车对象
32         HttpSession session=request.getSession();
33         shopingCart sc=(shopingCart)session.getAttribute("sc");
34         if(sc==null) {
35             sc=new shopingCart();
36             session.setAttribute("sc", sc);
37         }
38         //将点击的事件放入购物车
39         sc.addToCart(bookName, price);
40         //准备响应的JSON对象
41         StringBuilder result=new StringBuilder();
42         result.append("{")
43             .append("\"bookName\":\""+bookName+"\"")
44             .append(",")
45             .append("\"totalBookName\":\""+sc.totalBookNumer()+"\"")
46             .append(",")
47             .append("\"totalPrice\":\""+sc.totalBookPrice()+"\"")
48             .append("}");
49         
50         //响应JSON对象
51         response.setContentType("text/javascript");
52         response.getWriter().print(result.toString());
53     }
54 
55     
56 }

 

5.index.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 <script type="text/javascript" src="${pageContext.request.contextPath}/shopcart/jquery-3.2.1.min.js"></script>
 9 <script type="text/javascript">
10     $(function(){
11         $("a").click(function(){
12             alert(1);
13             var url=this.href;
14             var args={"time":new Date()};
15             $.getJSON(url,args,function(data){
16                 $("#bookName").text(data.bookName);
17                 $("#totalBookName").text(data.totalBookName);
18                 $("#totalPrice").text(data.totalPrice);
19             });
20             return false;
21         })
22     })
23 </script>
24 </head>
25 <body>
26         你已经将&nbsp;<span id="bookName"></span>&nbsp;加入到购物车中,
27         购物车中有&nbsp;<span id="totalBookName"></span>&nbsp;本书,
28         总价&nbsp;<span id="totalPrice"></span>&nbsp;<br><br>
29 
30     Java<a href="${pageContext.request.contextPath}/addToCart?id=java&price=100">加入购物车</a><br>
31     Oracle<a href="${pageContext.request.contextPath}/addToCart?id=Oracle&price=100">加入购物车</a><br>
32     Ajax<a href="${pageContext.request.contextPath}/addToCart?id=Ajax&price=100">加入购物车</a><br>
33 </body>
34 </html>

 

6.效果

  

 

package shoppingcart.biz; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * 购物车 */ public class ShoppingCart { private Map cartMap = null; //保存Product的Map /** * 购物车构造函数 */ public ShoppingCart(){ cartMap = new HashMap(); } /** * 取得存放产品的cartMap */ public Map getCartMap(){ return this.cartMap; } /** * 向购物车添加产品 */ public boolean addProduct(String productId){ if(existProduct(productId)){ // 产品已存在则增加数量 Product product = cartMap.get(productId); product.setProductNum(product.getProductNum() + 1); return true; } else{ // 否则新加入该产品 Product product = new Product(productId); if(product.getProductId()==null){ return false; // 数据库无该产品 }else{ cartMap.put(productId, product); return false; } } } /** * 检查购物车里是否已存在该产品 */ public boolean existProduct(String productId){ Iterator hmkey = cartMap.keySet().iterator(); while(hmkey.hasNext()){ String pid = hmkey.next(); if(pid.equals(productId)){ return true; } } return false; } /** * 从购物车移除指定产品 */ public void delProduct(String productId){ cartMap.remove(productId); } /** * 获取购物车产品数量 */ public int getProductNum(){ int productNum = 0; Iterator hmEntry = cartMap.values().iterator(); while(hmEntry.hasNext()){ productNum += hmEntry.next().getProductNum(); } return productNum; } /** * 统计购物车商品总价 */ public double getTotalprice(){ double totalPrice = 0.0; Iterator hmkey = cartMap.keySet().iterator(); Product product = null; while(hmkey.hasNext()){ product = cartMap.get(hmkey.next()); totalPrice += product.getProductPirce() * product.getProductNum(); } return totalPrice; } /** * 清空购物车 */ public void clearCart(){ cartMap.clear(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值