实现购物车

来源:互联网 发布:ug编程 编辑:程序博客网 时间:2024/06/11 04:27

创建一个订单类

public class CartItem {
    private Product product;
    private int buyNum;
    private double subTotal;
    public Product getProduct() {
        return product;
    }
    public void setProduct(Product product) {
        this.product = product;
    }
    public int getBuyNum() {
        return buyNum;
    }
    public void setBuyNum(int buyNum) {
        this.buyNum = buyNum;
    }
    public double getSubTotal() {
        return subTotal;
    }
    public void setSubTotal(double subTotal) {
        this.subTotal = subTotal;
    }
}

创建一个购物车类

public class Cart {
    private HashMap<String, CartItem> cartitems=new HashMap<String, CartItem>();
    private double total;
    
    public HashMap<String, CartItem> getCartitems() {
        return cartitems;
    }
    public void setCartitems(HashMap<String, CartItem> cartitems) {
        this.cartitems = cartitems;
    }
    public double getTotal() {
        return total;
    }
    public void setTotal(double total) {
        this.total = total;
    }
    
}

购物车的实现方法

public void addProductToCar(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String pid=request.getParameter("pid");
        Product product=ps.findProductByPid(pid);
        int buyNum=Integer.parseInt(request.getParameter("quantity"));
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        if(cart==null){
            cart=new Cart();
        }
        if(cart.getCartitems().containsKey(pid)){
            CartItem cartItem=cart.getCartitems().get(pid);
            cartItem.setBuyNum(cartItem.getBuyNum()+buyNum);
            cartItem.setSubTotal(cartItem.getSubTotal()+product.getShop_price()*buyNum);
            
        }else{
            CartItem cartItem=new CartItem();
            cartItem.setProduct(product);
            cartItem.setBuyNum(buyNum);
            cartItem.setSubTotal(cartItem.getProduct().getShop_price()*buyNum);
            cart.getCartitems().put(pid, cartItem);
        }
        cart.setTotal(cart.getTotal()+product.getShop_price()*buyNum);
        request.getSession().setAttribute("cart", cart);
        response.sendRedirect("/KSShopping/cart.jsp");
        
    }
    public void deleteItem(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        Map<String, CartItem> map=cart.getCartitems();
        String pid=request.getParameter("pid");
        CartItem ci=map.get(pid);
        cart.setTotal(cart.getTotal()-ci.getSubTotal());
        map.remove(pid);
        request.getSession().setAttribute("cart", cart);
        response.sendRedirect("/KSShopping/cart.jsp");
    }
    public void clearCart(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("cart");
        response.sendRedirect("/KSShopping/cart.jsp");
    }
    public void updateItem(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        Map<String, CartItem> map=cart.getCartitems();
        String pid=request.getParameter("pid");
        int quantity=Integer.parseInt(request.getParameter("quantity"));
        CartItem ci=map.get(pid);
        cart.setTotal(cart.getTotal()-ci.getSubTotal());
        ci.setBuyNum(quantity);
        ci.setSubTotal(ci.getBuyNum()*ci.getProduct().getShop_price());
        cart.setTotal(cart.getTotal()+ci.getSubTotal());
        response.sendRedirect("/KSShopping/cart.jsp");
    }
    public void updateItemAjax(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        Map<String, CartItem> map=cart.getCartitems();
        String pid=request.getParameter("pid");
        int quantity=Integer.parseInt(request.getParameter("quantity"));
        CartItem ci=map.get(pid);
        cart.setTotal(cart.getTotal()-ci.getSubTotal());
        ci.setBuyNum(quantity);
        ci.setSubTotal(ci.getBuyNum()*ci.getProduct().getShop_price());
        cart.setTotal(cart.getTotal()+ci.getSubTotal());
        String jsonStr="{'subTotal':"+ci.getSubTotal()+",'total':"+cart.getTotal()+"}";
        response.getWriter().println(jsonStr);
    }
    
}

购物车的页面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>商城购物车</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
<style>
body {
    margin-top: 20px;
    margin: 0 auto;
}

.carousel-inner .item img {
    width: 100%;
    height: 300px;
}

font {
    color: #3164af;
    font-size: 18px;
    font-weight: normal;
    padding: 0 10px;
}
</style>
<script type="text/javascript">
    function deleteItem(pid){
        location.href = "${pageContext.request.contextPath}/product?method=deleteItem&&pid="+pid;
    }
    function updateItem(pid){
        var quantity = document.getElementById("quantity").value;
        location.href = "${pageContext.request.contextPath}/product?method=updateItem&&pid="+pid+"&&quantity="+quantity;
    }
    function update(pid){
        var quantity = $("#"+pid+"quantity").val();
        if (quantity == ""){
            $("#"+pid+"quantity").val(1);
            quantity = 1;
        }
        $.ajax({
            url: "${pageContext.request.contextPath}/product?method=updateItemAjax",
            data:{"pid":pid,"quantity":quantity},
            type:"post",
            dataType:"json",
            success:function(data){
                $("#"+pid).text("¥"+data.subTotal);
                $("#total").text("¥"+data.total+"元");
            },
            error:function(e){
                alert(e.status);
            }
        });
    }
</script>
</head>

<body>
    <!-- 引入header.jsp -->
    <jsp:include page="/header.jsp"></jsp:include>

    <div class="container">
        <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 var="entry" items="${cart.cartitems}">
                        <c:set var="carItem" value="${entry.value}"></c:set>
                            <tr class="active">
                                <td width="60" width="40%"><input type="hidden" name="id"
                                    value="22"> <img src="${pageContext.request.contextPath}/${carItem.product.pimage}" width="70"
                                    height="60"></td>
                                <td width="30%"><a target="_blank">${carItem.product.pname}</a></td>
                                <td width="20%">¥${carItem.product.shop_price}</td>
                                <td width="10%"><input type="text" name="quantity"
                                    value="${carItem.buyNum}" maxlength="4" id="${carItem.product.pid}quantity" size="10" oninput="update(${carItem.product.pid})"></td>
                                <td width="15%"><span class="subtotal" id="${carItem.product.pid}">¥${carItem.subTotal}</span></td>
                                <td><a href="javascript:deleteItem(${carItem.product.pid})" class="delete">删除</a>
                                    <a href="javascript:updateItem(${carItem.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;">596</em>&nbsp; 商品金额: <strong
                    style="color:#ff6600;" id="total">¥${cart.total}元</strong>
            </div>
            <div style="text-align:right;margin-top:10px;margin-bottom:10px;">
                <a href="${pageContext.request.contextPath}/product?method=clearCart" id="clear" class="clear">清空购物车</a> <a
                    href="${pageContext.request.contextPath}/mlogin/order?method=submitOrders"> <input type="submit" width="100"
                    value="提交订单" name="submit" border="0"
                    style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
                        height:35px;width:100px;color:white;">
                </a>
            </div>
        </div>
    </div>

    <!-- 引入footer.jsp -->
    <jsp:include page="/footer.jsp"></jsp:include>
</body>

</html>



原创粉丝点击