购物车模块

抽取购物车模型

  1. 购物项:图片路径,商品名称,商品价格,购买数量,小计
public class CartItem {
	private Product product;//目的携带购物项3种参数(图片路径,商品名称,商品价格)
	private int num;//当前类别商品数量
	private double subTotal;//小计
	
	//小计是经过计算可以获取到的
	public double getSubTotal() {
		return product.getShop_price()*num;
	}
	
	public Product getProduct() {
		return product;
	}
	
	public void setProduct(Product product) {
		this.product = product;
	}
	
	public int getNum() {
		return num;
	}
	
	public void setNum(int num) {
		this.num = num;
	}
	
	public void setSubTotal(double subTotal) {
		this.subTotal = subTotal;
	}
	
}
  1. 购物车:购物项不确定
//2个属性3个方法
public class Cart {
    //总计/积分
    private double total = 0;
    //个数不确定的购物项 商品pid<===>CartItem
    Map<String, CartItem> map = new HashMap<>();
    //添加购物项到购物车
    //当用户点击加入购物车按钮,可以将当前要购买的商品id,商品数量发送到服务端,服务端根据商品id查询到商品信息
    //有了商品信息Product对象,有了要购买商品数量,当前的购物项也就可以获取到了
    public void addCartItemToCar(CartItem cartItem) {
        //获取到正在想购物车中添加的商品pid
        String pid = cartItem.getProduct().getPid();
        //将当前的购物项加入购物车之前,判断之前是否买过这类商品
        //如果没有买过    list.add(cartItem);
        //如果买过: 获取到原先的数量,获取到本次的数量,相加之后设置到原先购物项上
        if (map.containsKey(pid)) {
            //获取到原先的购物项
            CartItem oldItem = map.get(pid);
            oldItem.setNum(oldItem.getNum() + cartItem.getNum());

        } else {
            map.put(pid, cartItem);
        }
    }


    //返回MAP中所有的值
    public Collection<CartItem> getCartItems() {
        return map.values();
    }

    //移除购物项
    public void removeCartItem(String pid) {
        map.remove(pid);
    }

    //清空购物车
    public void clearCart() {
        map.clear();
    }

    //总计是可以经过计算获取到
    public double getTotal() {
        //向让总计请0
        total = 0;
        //获取到Map中所有的购物项
        Collection<CartItem> values = map.values();

        //遍历所有的购物项,将购物项上的小计相加
        for (CartItem cartItem : values) {
            total += cartItem.getSubTotal();
        }

        return total;
    }


    public void setTotal(double total) {
        this.total = total;
    }

    public Map<String, CartItem> getMap() {
        return map;
    }


    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }
}

添加商品到购物车

开发流程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k1wTaqif-1607233626735)(添加商品到购物车开发流程.png)]

设置form表单,设置隐藏域向服务端传递商品pid

<div style="padding:10px;border:1px solid #e7dbb1;width:330px;margin:15px 0 10px 0;;background-color: #fffee6;">
    <div style="margin:5px 0 10px 0;">白色</div>

    <div style="border-bottom: 1px solid #faeac7;margin-top:20px;padding-left: 10px;">购买数量:

        <!-- 向服务端发送 购买数量-->
        <input id="quantity" name="quantity" value="1" maxlength="4" size="10" type="text"> </div>
    <!-- 向服务端发送 商品pid-->
    <input type="hidden" name="pid" value="${product.pid}"/>


    <div style="margin:20px 0 10px 0;;text-align: center;">
        <%--加入到购物车 --%>
        <!-- 取消链接的默认行为 -->
        <a href="javascript:void(0)">
            <input id="btnId" style="background: url('${pageContext.request.contextPath}/img/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0);height:36px;width:127px;" value="加入购物车" type="button">
        </a> &nbsp;收藏商品</div>
</div>

如果一个表单中有多个按钮,点击不同按钮提交到不同路径

<script>
    $(function(){
        $("#btnId").click(function(){
            var formObj=document.getElementById("myForm");
            //formObj.action="${pageContext.request.contextPath}/cartServlet";
            //formObj.method="get";
            formObj.submit();
        });
    });
</script>

在cartServlet下添加addCartItemToCart方法

public String addCartItemToCart(HttpServletRequest request, HttpServletResponse response) throws Exception {

    //从session中获取购物车
    Cart cart = (Cart) request.getSession().getAttribute("cart");
    if (cart == null) {
        cart = new Cart();
        request.getSession().setAttribute("cart",cart);
    }
    //获取商品pid和数量
    String pid = request.getParameter("pid");
    int num = Integer.parseInt(request.getParameter("quantity")) ;
    //查询pid的商品
    ProductService productService = new ProductServiceImp();
    Product product = productService.findProductByPid(pid);
    //添加购物项
    CartItem cartItem = new CartItem();
    cartItem.setNum(num);
    //添加购物项到购物车
    cartItem.setProduct(product);
    cart.addCartItemToCar(cartItem);
    //重定向到/jsp/cart.jsp
    //如果转发,则刷新页面会提交,每次刷新商品数量都会+1
    response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
    return  null;
}

编写购物车页面jsp/cart.jsp

<div class="container">
    <c:if test="${empty cart.cartItems}">
        <div class="col-md-12">购物车中暂无数据,赶紧剁手去吧!</div>
    </c:if>

    <c:if test="${not empty cart.cartItems }">
        <div class="row">
            <div style="margin:0 auto; margin-top:10px;width:950px;">
                <strong style="font-size:16px;margin:5px 0;">订单详情</strong>
                <table class="table table-bordered">
                    <tbody>
                    <tr class="warning">
                        <th>图片</th>
                        <th>商品</th>
                        <th>价格</th>
                        <th>数量</th>
                        <th>小计</th>
                        <th>操作</th>
                    </tr>
                    <c:forEach items="${cart.cartItems}" var="item">
                        <tr class="active">
                            <td width="60" width="40%">
                                <input type="hidden" name="id" value="22">
                                <img src="${pageContext.request.contextPath}/${item.product.pimage}" width="70"
                                     height="60">
                            </td>
                            <td width="30%">
                                <a target="_blank">${item.product.pname}</a>
                            </td>
                            <td width="20%">
                                ¥${item.product.shop_price}
                            </td>
                            <td width="10%">
                                <input type="text" name="quantity" value="${item.num}" maxlength="4" size="10">
                            </td>
                            <td width="15%">
                                <span class="subtotal">¥${item.subTotal}</span>
                            </td>
                            <td>
                                    <%-- <a href="javascript:void(0);" class="delete" onclick="delCart(${item.product.pid})">删除</a> --%>
                                <input type="hidden" name="pid" value="${item.product.pid}"/>
                                <a href="javascript:void(0);" title="${item.product.pid}" class="delete"
                                   id="${item.product.pid}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>

        <div style="margin-right:130px;">
            <div style="text-align:right;">
                <em style="color:#ff6600;">
                    登录后确认是否享有优惠&nbsp;&nbsp;
                </em> 赠送积分: <em style="color:#ff6600;">${cart.total}</em>&nbsp; 商品金额: <strong
                    style="color:#ff6600;">¥${cart.total}</strong>
            </div>
            <div style="text-align:right;margin-top:10px;margin-bottom:10px;">
                <a href="javascript:void(0)" id="clear" class="clear">清空购物车</a>

                <a href="${pageContext.request.contextPath}/OrderServlet?method=saveOrder">
                        <%--提交表单 --%>
                    <input type="button" width="100" value="提交订单" name="submit" border="0"
                           style="background: url('${pageContext.request.contextPath}/img/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
                                   height:35px;width:100px;color:white;">
                </a>
            </div>
        </div>

    </c:if>
</div>

商品移除和清空购物车

绑定点击事件

<script>

    $(function () {
        $("#clear").click(function () {
            if (confirm("忍心删除我吗?")) {
                location.href = "${pageContext.request.contextPath}/cartServlet?method=clearCart";
            }
        });


        $(".delete").click(function () {
            var pid = this.id;
            if (confirm("忍心删除我吗?")) {
                location.href = "${pageContext.request.contextPath}/cartServlet?method=delCartItem&pid=" + pid;
            }
        });
    });
</script>

在cartServlet下添加delCartItem方法和clearCart方法

添加delCartItem方法

public String delCartItem(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //获取删除商品的pid
    String id = request.getParameter("pid");
    //获取购物车
    Cart cart = (Cart) request.getSession().getAttribute("cart");
    cart.removeCartItem(id);
    //重定向到/jsp/cart.jsp
    response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
    return null;
}

添加clearCart方法

public String clearCart(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //获取购物车
    Cart cart = (Cart) request.getSession().getAttribute("cart");
    cart.clearCart();
    //重定向到/jsp/cart.jsp
    response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
    return null;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一大岐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值