首页 > 技术文章 > D15 Sping Boot 入门 Sping框架--Java Web之书城项目(六) 购物车模块

nuister 2020-04-12 12:55 原文

需求分析

 购物车模块(Session方法)

   Ⅰ、购物车模型创建

    在com.gychen.pojo里创建CartItem商品项对象和Cart购物车对象

 1 package com.gychen.pojo;
 2 
 3 import java.math.BigDecimal;
 4 
 5 /**
 6  * 购物车商品项
 7  */
 8 public class CartItem {
 9 
10     private Integer id;
11     private String name;
12     private Integer count;
13     private BigDecimal price;
14     private BigDecimal totalPrice;
15 
16     public Integer getId() {
17         return id;
18     }
19 
20     public void setId(Integer id) {
21         this.id = id;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public Integer getCount() {
33         return count;
34     }
35 
36     public void setCount(Integer count) {
37         this.count = count;
38     }
39 
40     public BigDecimal getPrice() {
41         return price;
42     }
43 
44     public void setPrice(BigDecimal price) {
45         this.price = price;
46     }
47 
48     public BigDecimal getTotalPrice() {
49         return totalPrice;
50     }
51 
52     public void setTotalPrice(BigDecimal totalPrice) {
53         this.totalPrice = totalPrice;
54     }
55 
56 
57     /**
58      * 商品项信息
59      * @param id 商品id
60      * @param name 商品名称
61      * @param count 商品数量
62      * @param price 商品单价
63      * @param totalPrice 商品总价
64      */
65     public CartItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice) {
66         this.id = id;
67         this.name = name;
68         this.count = count;
69         this.price = price;
70         this.totalPrice = totalPrice;
71     }
72 
73 
74     public CartItem() {
75     }
76 
77     @Override
78     public String toString() {
79         return "CartItem{" +
80                 "id=" + id +
81                 ", name='" + name + '\'' +
82                 ", count=" + count +
83                 ", price=" + price +
84                 ", totalPrice=" + totalPrice +
85                 '}';
86     }
87 }
88 
89 CartItem.java
CartItem.java
 1 package com.gychen.pojo;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 /**
 8  * 购物车对象
 9  */
10 public class Cart {
11 
12     private Integer totalCount;
13     private BigDecimal totalPrice;
14     private List<CartItem> items = new ArrayList<CartItem>();
15 
16 
17     public Integer getTotalCount() {
18         return totalCount;
19     }
20 
21     public void setTotalCount(Integer totalCount) {
22         this.totalCount = totalCount;
23     }
24 
25     public BigDecimal getTotalPrice() {
26         return totalPrice;
27     }
28 
29     public void setTotalPrice(BigDecimal totalPrice) {
30         this.totalPrice = totalPrice;
31     }
32 
33     public List<CartItem> getItems() {
34         return items;
35     }
36 
37     public void setItems(List<CartItem> items) {
38         this.items = items;
39     }
40 
41 
42     public Cart(Integer totalCount, BigDecimal totalPrice, List<CartItem> items) {
43         this.totalCount = totalCount;
44         this.totalPrice = totalPrice;
45         this.items = items;
46     }
47 
48     public Cart() {
49     }
50 
51 
52     @Override
53     public String toString() {
54         return "Cart{" +
55                 "totalCount=" + totalCount +
56                 ", totalPrice=" + totalPrice +
57                 ", items=" + items +
58                 '}';
59     }
60 }
61 
62 Cart.java
Cart.java

    在Cart对象中添加需要的方法

  1 package com.gychen.pojo;
  2 
  3 import java.math.BigDecimal;
  4 import java.util.LinkedHashMap;
  5 import java.util.Map;
  6 
  7 /**
  8  * 购物车对象
  9  */
 10 public class Cart {
 11 
 12 //    private Integer totalCount;
 13 //    private BigDecimal totalPrice;
 14     /**
 15      * key是商品编号
 16      * value是商品信息
 17      */
 18     private Map<Integer,CartItem> items = new LinkedHashMap<Integer, CartItem>();
 19 
 20 
 21     /**
 22      * 添加商品项
 23      * @param cartItem 商品项对象
 24      */
 25     public void addItem(CartItem cartItem){
 26 
 27         //先查看购物车中是否已经添加过此商品
 28         //1、如果已添加,则数量+1
 29         //2、如果未添加,直接方到集合中即可
 30         CartItem item = items.get(cartItem.getId());
 31         if (item == null){
 32             //之前没有添加过此商品
 33             items.put(cartItem.getId(),cartItem);
 34         }else {
 35 
 36             //已经添加过的情况  数量+1,总价更新
 37             item.setCount(item.getCount() + 1);  //数量累加
 38             item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));  //更新总金额
 39         }
 40 
 41     }
 42 
 43 
 44 
 45     /**
 46      * 删除商品项
 47      * @param id 商品项id
 48      */
 49     public void deleteItem(Integer id){
 50 
 51         items.remove(id);
 52     }
 53 
 54 
 55     /**
 56      * 清空购物车
 57      */
 58     public void clear(){
 59 
 60         items.clear();
 61     }
 62 
 63 
 64     /**
 65      * 修改商品数量
 66      * @param id 商品项id
 67      * @param count 商品数量
 68      */
 69     public void uppdateCount(Integer id, Integer count){
 70 
 71         //先查看购物车是否有此商品,如果有修改数量,更新总金额
 72 
 73         CartItem cartItem = items.get(id);
 74         if (cartItem != null){
 75             cartItem.setCount(count); //修改商品数量
 76             cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));  //更新总金额
 77         }
 78     }
 79 
 80 
 81 
 82 
 83 
 84     private Integer getTotalCount() {
 85         Integer totalCount = 0;
 86         //法一:遍历Map集合中的每个键值对
 87         for (Map.Entry<Integer,CartItem>entry : items.entrySet()){
 88             totalCount += entry.getValue().getCount();
 89         }
 90 //        //法二:
 91 //        for (CartItem value : items.values()) {
 92 //            totalCount += value.getCount();
 93 //        }
 94         return totalCount;
 95     }
 96 
 97     //实际上并不需要
 98 //    public void setTotalCount(Integer totalCount) {
 99 //        this.totalCount = totalCount;
100 //    }
101 
102     private BigDecimal getTotalPrice() {
103         BigDecimal totalPrice = new BigDecimal(0);
104         for (Map.Entry<Integer,CartItem>entry : items.entrySet()){
105             totalPrice = totalPrice.add(entry.getValue().getTotalPrice());
106         }
107         return totalPrice;
108     }
109 
110 //    public void setTotalPrice(BigDecimal totalPrice) {
111 //        this.totalPrice = totalPrice;
112 //    }
113 
114     public Map<Integer,CartItem> getItems() {
115         return items;
116     }
117 
118     public void setItems(Map<Integer,CartItem> items) {
119         this.items = items;
120     }
121 
122 
123 
124     @Override
125     public String toString() {
126         return "Cart{" +
127                 "totalCount=" + getTotalCount() +
128                 ", totalPrice=" + getTotalPrice() +
129                 ", items=" + items +
130                 '}';
131     }
132 }
133 
134 Cart.java
Cart.java

    添加CartTest测试

 1 package com.gychen.test;
 2 
 3 import com.gychen.pojo.Cart;
 4 import com.gychen.pojo.CartItem;
 5 import org.junit.Test;
 6 
 7 import java.math.BigDecimal;
 8 
 9 import static org.junit.Assert.*;
10 
11 public class CartTest {
12 
13 
14     @Test
15     public void addItem() {
16         Cart cart = new Cart();
17         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(200),new BigDecimal(200)));
18         cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(100),new BigDecimal(100)));
19         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(200),new BigDecimal(200)));
20         System.out.println(cart);
21     }
22 
23     @Test
24     public void deleteItem() {
25         Cart cart = new Cart();
26         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(300),new BigDecimal(300)));
27         cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(100),new BigDecimal(100)));
28         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(300),new BigDecimal(300)));
29 
30         cart.deleteItem(1);
31 
32         System.out.println(cart);
33     }
34 
35     @Test
36     public void clear() {
37 
38         Cart cart = new Cart();
39         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(400),new BigDecimal(400)));
40         cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(200),new BigDecimal(200)));
41         cart.addItem(new CartItem(1,"java从入门到精通",1,new BigDecimal(400),new BigDecimal(400)));
42 
43         cart.clear();
44 
45         System.out.println(cart);
46     }
47 
48     @Test
49     public void uppdateCount() {
50 
51         Cart cart = new Cart();
52         cart.addItem(new CartItem(1,"Spring从入门到精通",1,new BigDecimal(400),new BigDecimal(400)));
53         cart.addItem(new CartItem(2,"python从入门到精通",1,new BigDecimal(200),new BigDecimal(200)));
54         cart.addItem(new CartItem(1,"Spring从入门到精通",1,new BigDecimal(400),new BigDecimal(400)));
55 
56         cart.uppdateCount(2,4);
57         cart.uppdateCount(1,1);
58         System.out.println(cart);
59     }
60 }
CartTest.java

  Ⅱ、加入购物车功能的实现

1         //1、获取请求的参数
2         //2、调用BookService.queryBookById(id):Book得到图书的信息
3         //3、把图书信息转化为CartItem商品项
4         //4、调用Cart.addItem(cartItem);添加商品项
5         //4、重定向回列表页                    

    在com.gychen.web中新建CartServlet的addItem方法  

 1  private BookService bookService = new BookServiceImpl();
 2     /**
 3      * 添加购物车
 4      * @param req 请求
 5      * @param resp 响应
 6      */
 7     protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 8 
 9         //1、获取请求的参数
10         //2、调用BookService.queryBookById(id):Book得到图书的信息
11         //3、把图书信息转化为CartItem商品项
12         //4、调用Cart.addItem(cartItem);添加商品项
13         //5、重定向回列表页
14 
15         //1、获取请求的参数
16         int id = WebUtils.parseInt(req.getParameter("id"),0);
17 
18         //2、调用BookService.queryBookById(id):Book得到图书的信息
19 
20         Book book = bookService.querryBookById(id);
21 
22         //3、把图书信息转化为CartItem商品项
23         CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
24 
25         //4、调用Cart.addItem(cartItem);添加商品项
26         Cart cart = (Cart) req.getSession().getAttribute("cart");
27         if (cart == null){
28 
29             cart = new Cart();
30             req.getSession().setAttribute("cart",cart);
31         }
32 
33         cart.addItem(cartItem);
34 
35         //最后一个添加的商品名称
36         req.getSession().setAttribute("lastName",cartItem.getName());
37         //5、重定向回列表页
38         //获取浏览器访问时的地址再重定向回去
39         resp.sendRedirect(req.getHeader("Referer"));
40     }
addItem();
  1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2 <%--
  3   Created by IntelliJ IDEA.
  4   User: 99622
  5   Date: 2020/3/30
  6   Time: 20:18
  7   To change this template use File | Settings | File Templates.
  8 --%>
  9 <%@ page
 10         contentType="text/html;charset=UTF-8"
 11         language="java"
 12         errorPage="/error500.jsp"
 13         autoFlush="true"
 14         buffer="8kb"
 15 %>
 16 <!--
 17 errorPage表示错误后自动跳转到error500.jsp
 18 -->
 19 <!DOCTYPE html>
 20 <html>
 21 <head>
 22     <meta charset="UTF-8">
 23     <title>书城首页</title>
 24 
 25     <%-- 静态包含 base标签、css样式、jQuery文件 --%>
 26     <%@ include file="/pages/common/head.jsp"%>
 27 
 28 
 29 </head>
 30 <body>
 31 
 32 <div id="header">
 33     <img class="logo_img" alt="" src="static/img/logo.gif" >
 34     <span class="wel_word">网上书城</span>
 35     <div>
 36         <%--如果用户没有登陆,显示登录和注册--%>
 37         <c:if test="${empty sessionScope.user}">
 38             <a href="pages/user/login.jsp">登录</a> |
 39             <a href="pages/user/regist.jsp">注册</a>
 40         </c:if>
 41 
 42         <%--如果用户已经登陆,则显示登录成功之后的用户信息--%>
 43         <c:if test="${not empty sessionScope.user}">
 44             <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临书城</span>
 45             <a href="pages/order/order.jsp">我的订单</a>
 46             <a href="userServlet?action=logout">注销</a>&nbsp;&nbsp;
 47         </c:if>
 48         <a href="pages/cart/cart.jsp">购物车</a>
 49         <a href="pages/manager/manager.jsp">后台管理</a>
 50     </div>
 51 </div>
 52 
 53 <div id="main">
 54     <div id="book">
 55         <div class="book_cond">
 56             <form action="" method="get">
 57                 价格:<input id="min" type="text" name="min" value=""> 元 -
 58                 <input id="max" type="text" name="max" value=""> 59                 <input type="submit" value="查询" />
 60             </form>
 61         </div>
 62         <div style="text-align: center">
 63             <span>您的购物车中有3件商品</span>
 64             <div>
 65                 您刚刚将<span style="color: red">时间简史</span>加入到了购物车中
 66             </div>
 67         </div>
 68         <c:forEach items="${requestScope.page.items}" var="book">
 69             <div class="b_list">
 70             <div class="img_div">
 71                 <img class="book_img" alt="" src="static/img/default.jpg" />
 72             </div>
 73                 <div class="book_info">
 74                     <div class="book_name">
 75                         <span class="sp1">书名:</span>
 76                         <span class="sp2">${book.name}</span>
 77                     </div>
 78                     <div class="book_author">
 79                         <span class="sp1">作者:</span>
 80                         <span class="sp2">${book.author}</span>
 81                     </div>
 82                     <div class="book_price">
 83                         <span class="sp1">价格:</span>
 84                         <span class="sp2">¥${book.price}</span>
 85                     </div>
 86                     <div class="book_sales">
 87                         <span class="sp1">销量:</span>
 88                         <span class="sp2">${book.sales}</span>
 89                     </div>
 90                     <div class="book_amount">
 91                         <span class="sp1">库存:</span>
 92                         <span class="sp2">${book.stock}</span>
 93                     </div>
 94                     <div class="book_add">
 95                         <button bookId="${book.id}" class="addToCart">加入购物车</button>
 96                     </div>
 97                 </div>
 98         </div>
 99         </c:forEach>
100 
101     </div>
102 
103     <div id="page_nav">
104         <%--大于1才显示首页--%>
105         <c:if test="${requestScope.page.pageNo > 1}">
106             <a href="client/clientbookServlet?action=page">首页</a>
107             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">
108                     上一页
109             </a>
110             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">
111                     ${requestScope.page.pageNo-1}
112             </a>
113         </c:if>
114 
115         <%--当前页码--%>
116         【${ requestScope.page.pageNo }】
117 
118         <%--小于末页才显示末页--%>
119         <c:if test="${requestScope.page.pageNo < requestScope.page.pageTotal}">
120             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">
121                     ${requestScope.page.pageNo+1}
122             </a>
123             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">
124                     下一页
125             </a>
126             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageTotal}">末页</a>
127         </c:if>
128 
129 
130         共${ requestScope.page.pageTotal }页,${ requestScope.page.pageTotalCount }条记录 到第
131         <input  value="${requestScope.page.pageNo}" name="pn" id="pn_input"/>132         <input id="searchPageBtn" type="button" value="确定">
133     </div>
134 
135 </div>
136 
137 <%--静态包含页脚内容--%>
138 <%@include file="/pages/common/footer.jsp"%>
139 <script>
140     $(function () {
141         $("#searchPageBtn").click(function () {
142             //获取要跳转的页面页码
143             var pageNo = $("#pn_input").val();
144             //location的href属性是地址栏的路由,执行请求转发
145             location.href="${pageScope.basePath}client/clientbookServlet?action=page&pageNo="+pageNo;
146         });
147 
148         // 给加购按钮绑定单击事件
149         $(".addToCart").click(function () {
150             var bookId = $(this).attr("bookId");
151 
152             location.href="${pageScope.basePath}cartServlet?action=addItem&id="+bookId;
153         })
154     });
155 </script>
156 </body>
157 </html>
index.jsp

   Ⅲ、删除购物车的商品项

    写deleteItem()方法

 1  /**
 2      * 删除购物车商品信息
 3      * @param req 请求
 4      * @param resp 响应
 5      */
 6     protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 7 
 8         //1、获取请求的参数
 9         //2、获取购物车对象
10         //3、删除购物车信息
11         //4、重定向回列表页
12 
13         //1、获取请求的参数,商品编号
14         int id = WebUtils.parseInt(req.getParameter("id"),0);
15 
16         //2、获取购物车对象
17 
18         Cart cart = (Cart) req.getSession().getAttribute("cart");
19         if (cart != null){
20             //删除购物车信息
21 
22             cart.deleteItem(id);
23 
24             //重定向回购物车
25             resp.sendRedirect(req.getHeader("Referer"));
26         }
27 
28     }
deleteItem();

  Ⅳ、清空购物车

    写clearCart();方法

 1 /**
 2      * 清空购物车
 3      * @param req 请求
 4      * @param resp 响应
 5      */
 6     protected void clearCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 7 
 8         //1、获取购物车对象
 9 
10         Cart cart = (Cart) req.getSession().getAttribute("cart");
11 
12         if (cart != null){
13 
14             //2、清空购物车
15             cart.clear();
16 
17             //重定向回购物车
18             resp.sendRedirect(req.getHeader("Referer"));
19         }
20 
21     }
clearCart();

  Ⅴ、修改购物车商品数量

 1 /**
 2      * 修改购物车商品数量
 3      * @param req 请求
 4      * @param resp 响应
 5      */
 6     protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 7 
 8         //1、获取请求的参数
 9         //2、获取购物车对象
10         //3、修改购物车商品数量
11         //4、重定向回列表页
12         
13         //1、获取请求的参数,商品编号
14         int id = WebUtils.parseInt(req.getParameter("id"),0);
15         int count = WebUtils.parseInt(req.getParameter("count"),0);
16 
17         //2、获取购物车对象
18 
19         Cart cart = (Cart) req.getSession().getAttribute("cart");
20         if (cart != null){
21 
22             //修改购物车商品数量
23             cart.uppdateCount(id,count);
24 
25             //重定向回购物车
26             resp.sendRedirect(req.getHeader("Referer"));
27         }
28 
29     }
updateCount

注:

  1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3 <!DOCTYPE html>
  4 <html>
  5 <head>
  6 <meta charset="UTF-8">
  7 <title>购物车</title>
  8     <%-- 静态包含 base标签、css样式、jQuery文件 --%>
  9     <%@ include file="/pages/common/head.jsp"%>
 10 </head>
 11 <body>
 12     
 13     <div id="header">
 14             <img class="logo_img" alt="" src="static/img/logo.gif" >
 15             <span class="wel_word">购物车</span>
 16             <%@include file="/pages/common/login_success_menu.jsp"%>
 17     </div>
 18     
 19     <div id="main">
 20     
 21         <table>
 22             <tr>
 23                 <td>商品名称</td>
 24                 <td>数量</td>
 25                 <td>单价</td>
 26                 <td>金额</td>
 27                 <td>操作</td>
 28             </tr>
 29 
 30             <c:forEach items="${sessionScope.cart.items}" var="entry">
 31             <tr>
 32                 <td>${entry.value.name}</td>
 33                 <td>
 34                     <input class="updateCount" type="text"
 35                            value="${entry.value.count}"
 36                            bookId="${entry.value.id}"
 37                            style="width: 60px;"
 38                            onkeyup="(this.v=function(){this.value=this.value.replace(/[^0-9-]+/,'');}).call(this)" onblur="this.v();">
 39                 </td>
 40                 <td>${entry.value.price}</td>
 41                 <td>${entry.value.totalPrice}</td>
 42                 <td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${entry.value.id}">删除</a></td>
 43             </tr>
 44             </c:forEach>
 45 
 46 
 47             <c:if test="${empty sessionScope.cart.items}">
 48                 <tr>
 49                     <td colspan="5"><a href="${pageScope.basePath}index.jsp">亲,当前购物车为空,快去浏览吧。</a></td>
 50                 </tr>
 51             </c:if>
 52         </table>
 53 
 54         <c:if test="${not empty sessionScope.cart.items}">
 55         <div class="cart_info">
 56             <span class="cart_span">购物车中共有<span class="b_count">${sessionScope.cart.totalCount}</span>件商品</span>
 57             <span class="cart_span">总金额<span class="b_price">${sessionScope.cart.totalPrice}</span></span>
 58             <span class="cart_span"><a class="clearCart" href="cartServlet?action=clearCart">清空购物车</a></span>
 59             <span class="cart_span"><a href="pages/cart/checkout.jsp">去结账</a></span>
 60         </div>
 61         </c:if>
 62 
 63 
 64     
 65     </div>
 66 
 67     <%--静态包含页脚内容--%>
 68     <%@include file="/pages/common/footer.jsp"%>
 69 
 70     <script>
 71         $(function () {
 72             //删除购物车商品事件
 73             $("a.deleteItem").click(function () {
 74                 return  confirm("您确定要删除【"+$(this).parent().parent().find("td:first").text()+"】吗?")
 75             });
 76 
 77             //清空购物车事件
 78             $("a.clearCart").click(function () {
 79                 return  confirm("您确定要清空购物车吗?")
 80             });
 81 
 82             //修改购物车商品数量事件
 83             $(".updateCount").change(function () {
 84 
 85                 var name = $(this).parent().parent().find("td:first").text();
 86                 var count = this.value;
 87                 var bookId = $(this).attr("bookId");
 88                 if (confirm("您确定要将【"+name+"】的数量修改为【"+count+"】吗?")){
 89                     //发起请求给服务器保存修改
 90                     location.href = "${pageScope.basePath}cartServlet?action=updateCount&count="+count+"&id="+bookId;
 91                 } else {
 92                     //defauleValue 是表单DOM默认值,即原来表单的值
 93                     this.value = this.defaultValue;
 94                 }
 95             });
 96         });
 97 
 98     </script>
 99 </body>
100 </html>
以上方法用到的前端cart.jsp
  1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2 <%--
  3   Created by IntelliJ IDEA.
  4   User: 99622
  5   Date: 2020/3/30
  6   Time: 20:18
  7   To change this template use File | Settings | File Templates.
  8 --%>
  9 <%--<%@ page--%>
 10 <%--        contentType="text/html;charset=UTF-8"--%>
 11 <%--        language="java"--%>
 12 <%--        errorPage="/error500.jsp"--%>
 13 <%--        autoFlush="true"--%>
 14 <%--        buffer="8kb"--%>
 15 <%--%>--%>
 16 <!--
 17 errorPage表示错误后自动跳转到error500.jsp
 18 -->
 19 
 20 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 21 <!DOCTYPE html>
 22 <html>
 23 <head>
 24     <meta charset="UTF-8">
 25     <title>书城首页</title>
 26 
 27     <%-- 静态包含 base标签、css样式、jQuery文件 --%>
 28     <%@ include file="/pages/common/head.jsp"%>
 29 
 30 
 31 </head>
 32 <body>
 33 
 34 <div id="header">
 35     <img class="logo_img" alt="" src="static/img/logo.gif" >
 36     <span class="wel_word">网上书城</span>
 37     <div>
 38         <%--如果用户没有登陆,显示登录和注册--%>
 39         <c:if test="${empty sessionScope.user}">
 40             <a href="pages/user/login.jsp">登录</a> |
 41             <a href="pages/user/regist.jsp">注册</a>
 42         </c:if>
 43 
 44         <%--如果用户已经登陆,则显示登录成功之后的用户信息--%>
 45         <c:if test="${not empty sessionScope.user}">
 46             <span>欢迎<span class="um_span">${sessionScope.user.username}</span>光临书城</span>
 47             <a href="pages/order/order.jsp">我的订单</a>
 48             <a href="userServlet?action=logout">注销</a>&nbsp;&nbsp;
 49         </c:if>
 50         <a href="pages/cart/cart.jsp">购物车</a>
 51         <a href="pages/manager/manager.jsp">后台管理</a>
 52     </div>
 53 </div>
 54 
 55 <div id="main">
 56     <div id="book">
 57         <div class="book_cond">
 58             <form action="" method="get">
 59                 价格:<input id="min" type="text" name="min" value=""> 元 -
 60                 <input id="max" type="text" name="max" value=""> 61                 <input type="submit" value="查询" />
 62             </form>
 63         </div>
 64         <div style="text-align: center">
 65 
 66 
 67             <c:if test="${not empty sessionScope.cart.items}">
 68                 <span>您的购物车中有${empty sessionScope.cart.totalCount?0:sessionScope.cart.totalCount}件商品</span>
 69                 <div>
 70                     您刚刚将<span style="color: red">${sessionScope.lastName}</span>加入到了购物车中
 71                 </div>
 72             </c:if>
 73 
 74             <c:if test="${empty sessionScope.cart.items}">
 75                 <span> </span>
 76                 <div>
 77                     <span style="color: red">当前购物车为空</span>
 78                 </div>
 79             </c:if>
 80         </div>
 81         <c:forEach items="${requestScope.page.items}" var="book">
 82             <div class="b_list">
 83             <div class="img_div">
 84                 <img class="book_img" alt="" src="static/img/default.jpg" />
 85             </div>
 86                 <div class="book_info">
 87                     <div class="book_name">
 88                         <span class="sp1">书名:</span>
 89                         <span class="sp2">${book.name}</span>
 90                     </div>
 91                     <div class="book_author">
 92                         <span class="sp1">作者:</span>
 93                         <span class="sp2">${book.author}</span>
 94                     </div>
 95                     <div class="book_price">
 96                         <span class="sp1">价格:</span>
 97                         <span class="sp2">¥${book.price}</span>
 98                     </div>
 99                     <div class="book_sales">
100                         <span class="sp1">销量:</span>
101                         <span class="sp2">${book.sales}</span>
102                     </div>
103                     <div class="book_amount">
104                         <span class="sp1">库存:</span>
105                         <span class="sp2">${book.stock}</span>
106                     </div>
107                     <div class="book_add">
108                         <button bookId="${book.id}" class="addToCart">加入购物车</button>
109                     </div>
110                 </div>
111         </div>
112         </c:forEach>
113 
114     </div>
115 
116     <div id="page_nav">
117         <%--大于1才显示首页--%>
118         <c:if test="${requestScope.page.pageNo > 1}">
119             <a href="client/clientbookServlet?action=page">首页</a>
120             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">
121                     上一页
122             </a>
123             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">
124                     ${requestScope.page.pageNo-1}
125             </a>
126         </c:if>
127 
128         <%--当前页码--%>
129         【${ requestScope.page.pageNo }】
130 
131         <%--小于末页才显示末页--%>
132         <c:if test="${requestScope.page.pageNo < requestScope.page.pageTotal}">
133             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">
134                     ${requestScope.page.pageNo+1}
135             </a>
136             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">
137                     下一页
138             </a>
139             <a href="client/clientbookServlet?action=page&pageNo=${requestScope.page.pageTotal}">末页</a>
140         </c:if>
141 
142 
143         共${ requestScope.page.pageTotal }页,${ requestScope.page.pageTotalCount }条记录 到第
144         <input  value="${requestScope.page.pageNo}" name="pn" id="pn_input"/>145         <input id="searchPageBtn" type="button" value="确定">
146     </div>
147 
148 </div>
149 
150 <%--静态包含页脚内容--%>
151 <%@include file="/pages/common/footer.jsp"%>
152 <script>
153     $(function () {
154         $("#searchPageBtn").click(function () {
155             //获取要跳转的页面页码
156             var pageNo = $("#pn_input").val();
157             //location的href属性是地址栏的路由,执行请求转发
158             location.href="${pageScope.basePath}client/clientbookServlet?action=page&pageNo="+pageNo;
159         });
160 
161         // 给加购按钮绑定单击事件
162         $(".addToCart").click(function () {
163             var bookId = $(this).attr("bookId");
164 
165             location.href="${pageScope.basePath}cartServlet?action=addItem&id="+bookId;
166         })
167     });
168 </script>
169 </body>
170 </html>
以上方法用到的前端index.jsp

 

推荐阅读