购物车案列

一、项目目录结构

  

 二、源代码

  dao包——dao层:BookDao.java

 1 package com.dao;
 2 
 3 import java.util.Map;
 4 
 5 import com.DB.DB;
 6 import com.domain.Book;
 7 
 8 
 9 
10 public class BookDao {
11     
12     public Map getAll(){
13         return DB.getAll();
14     }
15     
16     public Book find(String id){
17         return (Book) DB.getAll().get(id);
18     }
19 }

  

  DB包:DB.java——模拟数据库

  

 1 package com.DB;
 2 import java.util.LinkedHashMap;
 3 import java.util.Map;
 4 import com.domain.Book;
 5 import com.sun.org.apache.bcel.internal.generic.NEW;
 6 //代表数据库
 7 //代表数据库
 8 public class DB {
 9     
10     private static Map map = new LinkedHashMap();
11     static{
12         map.put("1", new Book("1","javaweb开发","老张",38,"一本好书"));
13         map.put("2", new Book("2","jdbc开发","老黎",18,"一本好书"));
14         map.put("3", new Book("3","ajax开发","老佟",328,"一本好书"));
15         map.put("4", new Book("4","jbpm开发","老毕",58,"一本好书"));
16         map.put("5", new Book("5","struts开发","老方",28,"一本好书"));
17         map.put("6", new Book("6","spring开发","老方",98,"一本好书"));
18     }
19     
20     
21     public static Map getAll(){
22         return map;
23     }
24     
25 }

  domain包:

   Book.java:书的实体类

 1 package com.domain;
 2 //书的实体类
 3 public class Book {
 4     
 5     private String id;
 6     private String name;
 7     private String author;
 8     private double price;
 9     private String description;
10     
11     
12     
13     
14     public Book() {
15         super();
16         // TODO Auto-generated constructor stub
17     }
18     public Book(String id, String name, String author, double price,
19             String description) {
20         super();
21         this.id = id;
22         this.name = name;
23         this.author = author;
24         this.price = price;
25         this.description = description;
26     }
27     public String getId() {
28         return id;
29     }
30     public void setId(String id) {
31         this.id = id;
32     }
33     public String getName() {
34         return name;
35     }
36     public void setName(String name) {
37         this.name = name;
38     }
39     public String getAuthor() {
40         return author;
41     }
42     public void setAuthor(String author) {
43         this.author = author;
44     }
45     public double getPrice() {
46         return price;
47     }
48     public void setPrice(double price) {
49         this.price = price;
50     }
51     public String getDescription() {
52         return description;
53     }
54     public void setDescription(String description) {
55         this.description = description;
56     }
57     
58     
59 }

   

  Cart.java:购物车类

    

 1 package com.domain;
 2 
 3 import java.util.LinkedHashMap;
 4 import java.util.Map;
 5 
 6 //代表用户的购物车
 7 
 8 //代表用户的购物车
 9 public class Cart {
10 
11     private Map<String,CartItem> map = new LinkedHashMap();
12     private double price;  //记住购物车所有商品多少钱
13     
14     public void add(Book book){
15         //看购物车中有没有,要添加的书对应的购物项
16         CartItem item = map.get(book.getId());
17         if(item==null){
18             item = new CartItem();
19             item.setBook(book);
20             item.setQuantity(1);
21             map.put(book.getId(), item);
22         }else{
23             item.setQuantity(item.getQuantity()+1);
24         }
25     }
26     
27     public Map<String, CartItem> getMap() {
28         return map;
29     }
30     public void setMap(Map<String, CartItem> map) {
31         this.map = map;
32     }
33     public double getPrice() {
34         double totalprice = 0;
35         for(Map.Entry<String, CartItem> entry : map.entrySet()){
36             CartItem item = entry.getValue();
37             totalprice += item.getPrice();
38         }
39         this.price = totalprice;
40         return price;
41     }
42     public void setPrice(double price) {
43         this.price = price;
44     }
45 }

  CartItem.java:购物项

    

 1 package com.domain;
 2 //用于代表某个商品,以及商品出现的次数(购物项)
 3 public class CartItem {
 4 
 5     private Book book;
 6     private int quantity;
 7     private double price;
 8     
 9     
10     public Book getBook() {
11         return book;
12     }
13     public void setBook(Book book) {
14         this.book = book;
15     }
16     public int getQuantity() {
17         return quantity;
18     }
19     public void setQuantity(int quantity) {
20         this.quantity = quantity;
21         this.price = this.book.getPrice() * this.quantity;
22     }
23     public double getPrice() {
24         return price;
25     }
26     public void setPrice(double price) {
27         this.price = price;
28     }
29 
30 }

   service包:service层

    BusinessService.java:
      

 1 package com.service;
 2 
 3 import java.util.Map;
 4 
 5 import com.dao.BookDao;
 6 import com.domain.Book;
 7 import com.domain.Cart;
 8 import com.domain.CartItem;
 9 //业务类,统一对web层提供所有服务
10 public class BusinessService {
11 
12     private BookDao dao = new BookDao();
13     
14     public Map getAllBook(){
15         return dao.getAll();
16     }
17     
18     public Book findBook(String id){
19         return dao.find(id);
20     }
21 
22     //删除购物车中的购物项
23     public void deleteCartItem(String id, Cart cart) {
24         cart.getMap().remove(id);
25     }
26     
27     //清空购物车
28     public void clearCart(Cart cart) {
29         cart.getMap().clear();
30     }
31     
32     //改变购物项的数量
33     public void changeItemQuantity(String id, String quantity, Cart cart) {
34         CartItem item = cart.getMap().get(id);
35         item.setQuantity(Integer.parseInt(quantity));
36     }
37     
38 }

    

  web层:

    ListBookServlet.java:显示所有书籍

      

 1 package com.web.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.Map;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import com.service.BusinessService;
13 //获取所有书籍
14 //获取所有书
15 public class ListBookServlet extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19 
20         BusinessService service = new BusinessService();
21         Map map = service.getAllBook();
22         request.setAttribute("map", map);
23         
24         request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response);
25     }
26 
27     public void doPost(HttpServletRequest request, HttpServletResponse response)
28             throws ServletException, IOException {
29         doGet(request, response);
30     }
31 
32 }

 

    BuyServlet.java:处理购买请求

      

 1 package com.web.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.domain.Book;
11 import com.domain.Cart;
12 import com.service.BusinessService;
13 
14 //完成书籍购买
15 //完成书籍购买
16 public class BuyServlet extends HttpServlet {
17 
18     public void doGet(HttpServletRequest request, HttpServletResponse response)
19             throws ServletException, IOException {
20 
21         String id = request.getParameter("id");
22         BusinessService service = new BusinessService();
23         Book book = service.findBook(id);
24         
25         //得到用户的购物车
26         Cart cart = (Cart) request.getSession().getAttribute("cart");
27         if(cart==null){
28             cart = new Cart();
29             request.getSession().setAttribute("cart", cart);
30         }
31         
32         //把书加到用户购物车中,完成购买
33         cart.add(book);
34         
35         //response.sendRedirect("/WEB-INF/jsp/listcart.jsp");
36         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
37         
38     }
39 
40     public void doPost(HttpServletRequest request, HttpServletResponse response)
41             throws ServletException, IOException {
42         doGet(request, response);
43     }
44 
45 }

    

    DeleteItemServlet.java:删除某一种商品

      

 1 package com.web.controller;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.domain.Cart;
11 import com.service.BusinessService;
12 //删除指定的购物项
13 public class DeleteItemServlet extends HttpServlet {
14 
15     public void doGet(HttpServletRequest request, HttpServletResponse response)
16             throws ServletException, IOException {
17 
18         String id = request.getParameter("id");
19         Cart cart = (Cart) request.getSession().getAttribute("cart");
20         
21         
22         BusinessService service = new BusinessService();
23         service.deleteCartItem(id,cart);
24         
25         //删除成功
26         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
27         
28     }
29 
30     public void doPost(HttpServletRequest request, HttpServletResponse response)
31             throws ServletException, IOException {
32         doGet(request, response);
33     }
34 
35 }

   

    ClearCartServlet.java:清空购物车

    

 1 package com.web.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.domain.Cart;
12 import com.service.BusinessService;
13 //清空购物车
14 public class ClearCartServlet extends HttpServlet {
15 
16     public void doGet(HttpServletRequest request, HttpServletResponse response)
17             throws ServletException, IOException {
18 
19         Cart cart = (Cart) request.getSession().getAttribute("cart");
20         
21         BusinessService service = new BusinessService();
22         service.clearCart(cart);
23         
24         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
25         
26     }
27 
28     public void doPost(HttpServletRequest request, HttpServletResponse response)
29             throws ServletException, IOException {
30         doGet(request, response);
31     }
32 
33 }

    

  ChangeQuantityServlet.java:修改购物车中指定商品的数量

    

 1 package com.web.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.domain.Cart;
12 import com.service.BusinessService;
13 
14 //把购物车中的书修改为指定数量
15 public class ChangeQuantityServlet extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19 
20         String id = request.getParameter("id");
21         String quantity = request.getParameter("quantity");
22         
23         Cart cart = (Cart) request.getSession().getAttribute("cart");
24         
25         BusinessService service = new BusinessService();
26         service.changeItemQuantity(id,quantity,cart);
27         
28 
29         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
30     }
31 
32     public void doPost(HttpServletRequest request, HttpServletResponse response)
33             throws ServletException, IOException {
34         doGet(request, response);
35     }
36 
37 }

   

  jsp页面:

  WebRoot/WEB-INF/jsp/listbook.jsp:显示书籍列表

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 
 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 5 <html>
 6   <head>
 7     <title>书籍列表页面</title>
 8   </head>
 9   
10   <body style="text-align: center">
11     
12     <h1>书籍列表</h1>
13     
14     <table width="70%" border="1">
15         <tr>
16             <td>书名</td>
17             <td>作者</td>
18             <td>售价</td>
19             <td>描述 </td>
20             <td>操作</td>
21         </tr>
22         <c:forEach var="entry" items="${map}">
23             <tr>
24                 <td>${entry.value.name }</td>
25                 <td>${entry.value.author }</td>
26                 <td>${entry.value.price }</td>
27                 <td>${entry.value.description } </td>
28                 <td>
29                     <a href="${pageContext.request.contextPath }/servlet/BuyServlet?id=${entry.value.id }" target="_blank">购买</a>
30                 </td>
31             </tr>
32         </c:forEach>
33     </table>
34     
35   </body>

    

  WebRoot/WEB-INF/jsp/listcart.jsp:显示购物车列表

    

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4 <html>
 5   <head>
 6     <title>购物车列表</title>
 7     
 8     <script type="text/javascript">
 9         function deleteitem(id){
10             var b = window.confirm("您确认删除吗??");
11             if(b){
12                 window.location.href="${pageContext.request.contextPath }/servlet/DeleteItemServlet?id="+id;
13             }
14         }
15         
16         function clearcart(){
17             var b = window.confirm("您确认清空吗??");
18             if(b){
19                 window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet";
20             }
21         }
22         
23         function changeQuantity(input,id,oldvalue){
24             var quantity = input.value;   //得到要修改的数量 sdfsfs
25             
26             /*
27             //检查用户输入的数量是不是一个数字
28             if(isNaN(quantity)){
29                 alert("请输入数字!!");
30                 input.value = oldvalue;
31                 return;
32             }
33             */
34             
35             //检查用户输入的数量是不是一个正整数
36             if(quantity<0 || quantity!=parseInt(quantity)){
37                 alert("请输入正整数!!");
38                 input.value = oldvalue;
39                 return;
40             }
41             
42             
43             
44             var b = window.confirm("您确认把书的数量修改为:" + quantity);
45             if(b){
46                 window.location.href="${pageContext.request.contextPath}/servlet/ChangeQuantityServlet?id=" + id + "&quantity=" + quantity;
47             }
48         }
49     </script>
50     
51   </head>
52   
53   <body style="text-align: center">
54     
55     <h1>购物车列表</h1>
56     
57     <c:if test="${empty(cart.map)}"> 
58         您没有购买任何商品!!!
59     </c:if>
60    
61    
62        <c:if test="${!empty(cart.map)}"> 
63     <table width="70%" border="1">
64         <tr>
65             <td>书名</td>
66             <td>作者</td>
67             <td>单价</td>
68             <td>数量 </td>
69             <td>小计</td>
70             <td>操作</td>
71         </tr>
72         <c:forEach var="entry" items="${cart.map}">
73             <tr>
74                 <td>${entry.value.book.name }</td>
75                 <td>${entry.value.book.author }</td>
76                 <td>${entry.value.book.price }</td>
77                 <td>
78                     <input type="text" name="quantity" value="${entry.value.quantity }" style="35px" onchange="changeQuantity(this,${entry.key},${entry.value.quantity})">
79                 </td>
80                 <td>${entry.value.price }</td>
81                 <td>
82                     <a href="javascript:void(0)" onclick="deleteitem(${entry.key })">删除</a>  <!-- 去掉超链接默认行为 -->
83                     
84                 </td>
85             </tr>
86         </c:forEach>
87         
88         <tr>
89             <td colspan="3">总价</td>
90             <td colspan="2">${cart.price }元</td>
91             <td colspan="1">
92                 <a href="javascript:void(0)" onclick="clearcart()">清空购物车</a>
93             </td>
94         </tr>
95     </table>
96      </c:if>
97     
98   </body>
99 </html>
原文地址:https://www.cnblogs.com/niuchuangfeng/p/9077503.html