第六阶段-尚硅谷书城案例-购物车模型用Session实现

1.购物车

思路分析:
在这里插入图片描述

1.1、购物车模型的创建

1.1.1、创建购物车商品项 CartItem
public class CartItem {
    private Integer id;
    private String name;
    private Integer count;
    private BigDecimal price;
    private BigDecimal totalPrice;
    }
1.1.2、创建购物车对象 Cart
package com.aiguigu.pojo;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

public class Cart {

    /**
     * key 是商品编号
     * value 是商品信息*/
    private Map<Integer,CartItem> items = new LinkedHashMap<Integer,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 claer(){
        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;
    }
}

获取重商品数量,和总商品价格 用 getTotalCount()、getTotalPrice()方法获取,参数 totalCount、totalPrice 直接在方法里面定义。用Map集合遍历
在这里插入图片描述

1.1.3、创建购物车程序 CartServlet
package com.aiguigu.web;

import com.aiguigu.pojo.Book;
import com.aiguigu.pojo.Cart;
import com.aiguigu.pojo.CartItem;
import com.aiguigu.service.BookService;
import com.aiguigu.service.impl.BookServiceImpl;
import com.aiguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CartServlet extends BaseServlet {

 }

  1. 添加购物车:
    因为是使用session版本,跳转用 js的location.href 来跳转

一:给加入购物车添加 class 并 通过 class 绑定点击事件,跳转到 CartServlet
在这里插入图片描述

<div class="book_add">
						<button bookId="${book.id}" class="addToCart">加入购物车</button>
					</div>

<script type="text/javascript">

		$(function () {
			$("button.addToCart").click(function () {

				var bookId = $(this).attr("bookId");
				location.href = "http://localhost:8080/book/cartServlet?action=addItem&id=" + bookId;
			});
		});
	</script>

在这里插入图片描述
在这里插入图片描述

二:CartServlet页面 编写 addItem 方法

public class CartServlet extends BaseServlet {
     private BookService bookService = new BookServiceImpl();
 protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        System.out.println(id);
        // 获取请求的参数 商品编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //调用 bookService.queryBookById(id) Book得到图书信息
        Book book = bookService.queryBookById(id);
        //调用 Caet.addItem(CaerItem);添加商品项
        CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
        //
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart",cart);
        }
        cart.addItem(cartItem);
        //将最后一个商品名字放入 session域中
        req.getSession().setAttribute("lastName",cartItem.getName());


        System.out.println("请求头Referer的值" + req.getHeader("Referer"));
        //重定向回原来商品所在地址页面
        resp.sendRedirect(req.getHeader("Referer") );

    }
}

在这里插入图片描述
在这里插入图片描述

运行结果:
在这里插入图片描述

1.1.4、购物车展示

动态输出 图书内容:
在这里插入图片描述
购物车为空时:

<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="items">
					<tr>
						<td>${items.value.name}</td>
						<td><input class="updateCount"  bookId="${items.value.id}" style="width: 80px;" type="text" value="${items.value.count}"></td>
						<td>${items.value.price}</td>
						<td>${items.value.totalPrice}</td>
						<td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${items.value.id}">删除</a></td>
					</tr>
				</c:forEach>
			</c:if>

在这里插入图片描述
当购物车为空时就不现实以上内容

<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 id="clearCart" href="cartServlet?action=clear">清空购物车</a></span>
			<span class="cart_span"><a href="pages/cart/checkout.jsp">去结账</a></span>
		</div>
		</c:if>
1.1.5、删除购物车中的商品项
<td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${items.value.id}">删除</a></td>

给删除 绑定click事件

$(function () {
			// 给 【删除】绑定单击事件
			$("a.deleteItem").click(function () {
				return confirm("确定要删除【"+ $(this).parent().parent().find("td:first").text() +"】吗")
			});

在 CartServlet 编写删除方法

     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"));
        }
    }

运行结果:
在这里插入图片描述

1.1.6、修改商品数量

分析:
在这里插入图片描述

在 cart.jsp 页面,将数量用输入框替代,修改商品数量需要获取商品的id 和 count

						<td><input class="updateCount"  bookId="${items.value.id}" style="width: 80px;" type="text" value="${items.value.count}"></td>

给 输入框绑定 change 事件:

//给修改【商品数量】 绑定 onchange事件
			$(".updateCount").change(function () {
				//获取商品名称
				var name = $(this).parent().parent().find("td:first").text();
				//获取商品数量
				var count = this.value;
				//获取商品id
				var id = $(this).attr("bookId");
				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;
				}
			});

在CartServlet 页面 编写 updateCount

 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) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.updateCount(id,count);
            resp.sendRedirect(req.getHeader("referer"));
        }

    }
1.1.7、清空购物车

在 Cart.jsp 页面修改 跳转页面和调用的方法

<span class="cart_span"><a id="clearCart" href="cartServlet?action=clear">清空购物车</a></span>

在 CartServlet层 编写 clear 方法

 protected void clear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取 购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null){
            cart.claer();
            resp.sendRedirect(req.getHeader("referer"));
        }
    }

当购物车为空时,提示用户去购物
在这里插入图片描述
当购物不为空时,显示图书信息

在这里插入图片描述

	<%-- 如果购物车非空的情况--%>
			<c:if test="${not empty sessionScope.cart.items}">
				<c:forEach items="${sessionScope.cart.items}" var="items">
					<tr>
						<td>${items.value.name}</td>
						<td><input class="updateCount"  bookId="${items.value.id}" style="width: 80px;" type="text" value="${items.value.count}"></td>
						<td>${items.value.price}</td>
						<td>${items.value.totalPrice}</td>
						<td><a class="deleteItem" href="cartServlet?action=deleteItem&id=${items.value.id}">删除</a></td>
					</tr>
				</c:forEach>
			</c:if>
			<%-- 如果购物车为空的情况--%>
			<c:if test="${ empty sessionScope.cart.items}">
				<tr>
					<td colspan="5"><a href="index.jsp">亲购物车为空快去浏览商品</a> </td>
					<
				</tr>
			</c:if>
1.1.8、首页回显购物车信息

在这里插入图片描述
分两种情况:

  1. 购物车不为空时显示:
<%--购物车不会空的情况--%>
				<c:if test="${not empty sessionScope.cart.items}">
					<span>您的购物车中有${sessionScope.cart.totalCount}件商品</span>
					<div>
						您刚刚将<span style="color: red">${sessionScope.lastName}</span>加入到了购物车中
					</div>
				</c:if>
  1. 购物车为空时显示:
<c:if test="${empty sessionScope.cart.items}">
					<span></span>
					<div>
						<span style="color: red">购物车为空</span>
					</div>
				</c:if>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值