书城项目第六、七阶段
今日任务
1、项目第六阶段:购物车
1.1、购物车模块分析
1.2、购物车模型编写
1.2.1、购物车模型:
/**
* 购物车的商品项
*/
public class CartItem {
private Integer id;
private String name;
private Integer count;
private BigDecimal price;
private BigDecimal totalPrice;
/**
* 购物车对象
*/
public class Cart {
// private Integer totalCount;
// private BigDecimal totalPrice;
/**
* key 是商品编号,
* value,是商品信息
*/
private Map<Integer,CartItem> items = new LinkedHashMap<Integer,CartItem>();
/**
* 添加商品项
*
* @param cartItem
*/
public void addItem(CartItem cartItem) {
// 先查看购物车中是否已经添加过此商品,如果已添加,则数量累加,总金额更新,如果没有添加过,直接放到
集合中即可
CartItem item = items.get(cartItem.getId());
if (item == null) {
// 之前没添加过此商品
items.put(cartItem.getId(), cartItem);
} else {
// 已经 添加过的情况
item.setCount( item.getCount() + 1 ); // 数量 累加
item.setTotalPrice( item.getPrice().multiply(new BigDecimal( item.getCount() )) ); // 更
新总金额
}
}
/**
* 删除商品项
*/
public void deleteItem(Integer id) {
items.remove(id);
}
/**
* 清空购物车
*/
public void clear() {
items.clear();
}
/**
* 修改商品数量
*/
public void updateCount(Integer id,Integer count) {
// 先查看购物车中是否有此商品。如果有,修改商品数量,更新总金额
CartItem cartItem = items.get(id);
if (cartItem != null) {
cartItem.setCount(count);// 修改商品数量
cartItem.setTotalPrice( cartItem.getPrice().multiply(new
BigDecimal( cartItem.getCount() )) ); // 更新总金额
}
}
public Integer getTotalCount() {
Integer totalCount = 0;
for (Map.Entry<Integer,CartItem>entry : items.entrySet()) {
totalCount += entry.getValue().getCount();
}
return totalCount;
}
public BigDecimal getTotalPrice() {
BigDecimal totalPrice = new BigDecimal(0);
for (Map.Entry<Integer,CartItem>entry : items.entrySet()) {
totalPrice = totalPrice.add(entry.getValue().getTotalPrice());
}
return totalPrice;
}
public Map<Integer, CartItem> getItems() {
return items;
}
public void setItems(Map<Integer, CartItem> items) {
this.items = items;
}
@Override
public String toString() {
return "Cart{" +
"totalCount=" + getTotalCount() +
", totalPrice=" + getTotalPrice() +
", items=" + items +
'}';
}
}
1.2.2、购物车的测试:
public class CartTest {
@Test
public void addItem() {
Cart cart = new Cart();
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(2, "数据结构与算法", 1, new BigDecimal(100),new BigDecimal(100)));
System.out.println(cart);
}
@Test
public void deleteItem() {
Cart cart = new Cart();
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(2, "数据结构与算法", 1, new BigDecimal(100),new BigDecimal(100)));
cart.deleteItem(1);
System.out.println(cart);
}
@Test
public void clear() {
Cart cart = new Cart();
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(2, "数据结构与算法", 1, new BigDecimal(100),new BigDecimal(100)));
cart.deleteItem(1);
cart.clear();
System.out.println(cart);
}
@Test
public void updateCount() {
Cart cart = new Cart();
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.addItem(new CartItem(2, "数据结构与算法", 1, new BigDecimal(100),new BigDecimal(100)));
cart.deleteItem(1);
cart.clear();
cart.addItem(new CartItem(1, "java从入门到精通", 1, new BigDecimal(1000),new BigDecimal(1000)));
cart.updateCount(1, 10);
System.out.println(cart);
}
}
1.3、加入购物车功能的实现
CartServlet 程序中的代码:
/**
* 加入购物车
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// 获取请求的参数 商品编号
int id = WebUtils.parseInt(req.getParameter("id"), 0);
// 调用 bookService.queryBookById(id):Book 得到图书的信息
Book book = bookService.queryBookById(id);
// 把图书信息,转换成为 CartItem 商品项
CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
// 调用 Cart.addItem(CartItem);添加商品项
Cart cart = (Cart) req.getSession().getAttribute("cart");
if (cart == null) {
cart = new Cart();
req.getSession().setAttribute("cart",cart);
}
cart.addItem(cartItem);
System.out.println(cart);
System.out.println("请求头 Referer 的值:" + req.getHeader("Referer"));
// 重定向回原来商品所在的地址页面
resp.sendRedirect(req.getHeader("Referer"));
}
index.jsp 页面 js 的代码:
图解说明,如何跳回添加商品的页面:
1.4、购物车的展示
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物车</title>
<%-- 静态包含 base 标签、css 样式、jQuery 文件 --%>
<%@ include file="/pages/common/head.jsp"%>
</head>
<body>
<div id="header">
<img class="logo_img" alt="" src="static/img/logo.gif" >
<span class="wel_word">购物车</span>
<%--静态包含,登录 成功之后的菜单 --%>
<%@ include file="/pages/common/login_success_menu.jsp"%>
</div>
<div id="main">
<table>
<tr>
<td>商品名称</td>
<td>数量</td>
<td>单价</td>
<td>金额</td>
<td>操作</td>
</tr>
<c:if test="${empty sessionScope.cart.items}">
<%--如果购物车空的情况--%>
<tr>
<td colspan="5"><a href="index.jsp">亲,当前购物车为空!快跟小伙伴们去浏览商品吧!!!</a>
</td>
</tr>
</c:if>
<c:if test="${not empty sessionScope.cart.items}">
<%--如果购物车非空的情况--%>
<c:forEach items="${sessionScope.cart.items}" var="entry">
<tr>
<td>${entry.value.name}</td>
<td>${entry.value.count}</td>
<td>${entry.value.price}</td>
<td>${entry.value.totalPrice}</td>
<td><a href="#">删除</a></td>
</tr>
</c:forEach>
</c:if>
</table>
<%--如果购物车非空才输出页面的内容--%>
<c:if test="${not empty sessionScope.cart.items}">
<div class="cart_info">
<span class="cart_span">购物车中共有<span
class="b_count">${sessionScope.cart.totalCount}</span>件商品</span>
<span class="cart_span">总金额<span
class="b_price">${sessionScope.cart.totalPrice}</span>元</span>
<span class="cart_span"><a href="#">清空购物车</a></span>
<span class="cart_span"><a href="pages/cart/checkout.jsp">去结账</a></span>
</div>
</c:if>
</div>
<%--静态包含页脚内容--%>
<%@include file="/pages/common/footer.jsp"%>
</body>
</html>
1.5、删除购物车商品项
CartServlet 程序:
/**
* 删除商品项
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void deleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException{
// 获取商品编号
int id = WebUtils.parseInt(req.getParameter("id"), 0);
// 获取购物车对象
Cart cart = (Cart) req.getSession().getAttribute("cart");
if (cart != null) {
// 删除 了购物车商品项
cart.deleteItem(id);
// 重定向回原来购物车展示页面
resp.sendRedirect(req.getHeader("Referer"));
}
}
购物车/pages/cart/cart.jsp 页面的代码:
删除的请求地址:
删除的确认提示操作:
<script type="text/javascript">
$(function () {
// 给 【删除】绑定单击事件
$("a.deleteItem").click(function () {
return confirm("你确定要删除【" + $(this).parent().parent().find("td:first").text() +"】吗?")
});
});
</script>
1.6、清空购物车
CartServlet 程序
/**
* 清空购物车
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException{
// 1 获取购物车对象
Cart cart = (Cart) req.getSession().getAttribute("cart");
if (cart != null) {
// 清空购物车
cart.clear();
// 重定向回原来购物车展示页面
resp.sendRedirect(req.getHeader("Referer"));
}
}
cart.jsp 页面的内容
给清空购物车添加请求地址,和添加 id 属性:
清空的确认提示操作:
// 给清空购物车绑定单击事件
$("#clearCart").click(function () {
return confirm("你确定要清空购物车吗?");
})
1.7、修改购物车商品数量
CartServlet 程序
/**
* 修改商品数量
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void updateCount(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException{
// 获取请求的参数 商品编号 、商品数量
int id = WebUtils.parseInt(req.getParameter("id"),0);
int count = WebUtils.parseInt(req.getParameter("count"), 1);
// 获取 Cart 购物车对象
Cart cart = (Cart) req.getSession().getAttribute("cart");
if (cart != null) {
// 修改商品数量
cart.updateCount(id,count);
// 重定向回原来购物车展示页面
resp.sendRedirect(req.getHeader("Referer"));
}
}
修改 pages/cart/cart.jsp 购物车页面:
修改商品数量 js 代码:
// 给输入框绑定 onchange 内容发生改变事件
$(".updateCount").change(function () {
// 获取商品名称
var name = $(this).parent().parent().find("td:first").text();
var id = $(this).attr('bookId');
// 获取商品数量
var count = this.value;
if ( confirm("你确定要将【" + name + "】商品修改数量为:" + count + " 吗?") ) {
//发起请求。给服务器保存修改
location.href =
"http://localhost:8080/book/cartServlet?action=updateCount&count="+count+"&id="+id;
} else {
// defaultValue 属性是表单项 Dom 对象的属性。它表示默认的 value 属性值。
this.value = this.defaultValue;
}
});
1.8、首页,购物车数据回显
在添加商品到购物车的时候,保存最后一个添加的商品名称:
在 pages/client/index.jsp 页面中输出购物车信息:
<div style="text-align: center">
<c:if test="${empty sessionScope.cart.items}">
<%--购物车为空的输出--%>
<span> </span>
<div>
<span style="color: red">当前购物车为空</span>
</div>
</c:if>
<c:if test="${not empty sessionScope.cart.items}">
<%--购物车非空的输出--%>
<span>您的购物车中有 ${sessionScope.cart.totalCount} 件商品</span>
<div>
您刚刚将<span style="color: red">${sessionScope.lastName}</span>加入到了购物车中
</div>
</c:if>
</div>