购物车实现原理

我们设计购物车就是一个 Map<Product,Integer>集合,这个Map集合要存储到session中。

一、将商品添加到购物车

  1.先在页面上添加一个链接

  2.在AddProductToCartServlet中

    1.先得到商品的id

    2.从数据库中通过id将商品查询出来。

    3.将商品添加到购物车

    a.从session中获取购物车,没有的话,重新new 出一个

    b.判断商品在购物车中是否存在,如果不存在,数量为1,如果存在,数量在原基础上加1

    c.将购物车重新装入到session中。

    问题:我们的购物使用的是一个HashMap集合,key是唯一的,保证key唯一的方式是通过hashCode与equals方法

    所以我们在使用时,需要将Product类的hashCode与equals方法重写。

    我们在重写时,只比较id值就可以。

重写代码:



    public class Product implements Serializable {

        // id VARCHAR(50) PRIMARY KEY,
        // NAME VARCHAR(30),
        // price DOUBLE,
        // COUNT INT,
        // category VARCHAR(20),
        // description VARCHAR(200)

        private String id;
        private String name;
        private double price;
        private int count;
        private String category;
        private String description;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public String getCategory() {
            return category;
        }

        public void setCategory(String category) {
            this.category = category;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        @Override
        public String toString() {
            return "Product [id=" + id + ", name=" + name + ", price=" + price
                    + ", count=" + count + ", category=" + category
                    + ", description=" + description + "]";
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Product other = (Product) obj;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            return true;
        }
        
        

    }

二、显示购物车商品

我们的购物车是存在于session中的。我们只需要在cart.jsp页面将session中的cartt这个Map集合得到,并显示出来就可以。

  1. 对购物车中商品操作  

在点击+或-号时可以修改购物车中商品的数量

 

当点击+或-按钮时,我们会调用一个javascript中的函数。changeCount();通过这个函数我们向服务器发送请求,在服务器端从session中获取购物车中数据,并根据提交的数据将购物车中指定的商品数量修改在返回到购物车页面展示。

Js代码:

服务器端代码

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>shop</title>
<link rel="stylesheet" href="css/main.css" type="text/css" />
<script type="text/javascript">
    //当点击+或-号时,会向服务器发送请求,并通知服务器修改哪个商品及数量是多少
    function changeCount(id, count, totalCount) {
        //将字符串转换成数字
        count = parseInt(count);
        totalCount = parseInt(totalCount);
        //确认删除功能
        if (count <= 0) {
            var flag = window.confirm("确认删除吗");
            if (!flag) { //取消时,直接让程序结束
                document.getElementById(id).value = 1;
                count = 1;
            } else {
                count = 0;
            }
        }
        //控制购买数量不能大于库存
        if (count > totalCount) {
            alert("最大购买数量为" + totalCount);
            document.getElementById(id).value = totalCount;
            count = totalCount;
            //return;
        }

        location.href = "${pageContext.request.contextPath}/changeCartCount?id="
                + id + "&count=" + count;
    }
</script>


</head>

<body class="main">

    <div id="divpagecontent">
        <table width="100%" border="0" cellspacing="0">
            <tr>

                <td><div style="text-align:right; margin:5px 10px 5px 0px">
                        <a href="index.html">首页</a>&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;&nbsp;&nbsp;&nbsp;购物车
                    </div>

                    <table cellspacing="0" class="infocontent">
                        <tr>
                            <td><img src="ad/page_ad.jpg" width="666" height="89" />
                                <table width="100%" border="0" cellspacing="0">
                                    <tr>
                                        <td><img src="images/buy1.gif" width="635" height="38" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <table cellspacing="1" class="carttable">
                                                <tr>
                                                    <td width="25%">序号</td>
                                                    <td width="15%">商品名称</td>
                                                    <td width="10%">价格</td>
                                                    <td width="20%">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数量</td>
                                                    <td width="10%">库存</td>
                                                    <td width="10%">小计</td>
                                                    <td width="10%">取消</td>
                                                </tr>
                                            </table> <c:forEach items="${cart}" var="entry">
                                                <table width="100%" border="0" cellspacing="0">
                                                    <tr>
                                                        <td width="25%">${entry.key.id}</td>
                                                        <td width="15%">${entry.key.name}</td>

                                                        <td width="10%">${entry.key.price }</td>
                                                        <td width="20%"><input type="button" value='-'
                                                            style="width:20px"
                                                            onclick="changeCount('${entry.key.id}','${entry.value-1}','${entry.key.count}')">

                                                            <input name="text" type="text" value="${entry.value}"
                                                            id="${entry.key.id}" style="width:40px;text-align:center"
                                                            onblur="changeCount('${entry.key.id}',this.value,'${entry.key.count}')" />

                                                            <input type="button" value='+' style="width:20px"
                                                            onclick="changeCount('${entry.key.id}','${entry.value+1}','${entry.key.count}')">

                                                        </td>
                                                        <td width="10%">${entry.key.count }</td>
                                                        <td width="10%">${entry.key.price*entry.value}</td>

                                                        <td width="10%"><a href="javascript:void(0);"
                                                            style="color:#FF0000; font-weight:bold"
                                                            onclick="changeCount('${entry.key.id}','0','${entry.key.count}')">X</a>

                                                        </td>
                                                    </tr>
                                                </table>
                                            </c:forEach>


                                            <table cellspacing="1" class="carttable">
                                                <tr>
                                                    <td style="text-align:right; padding-right:40px;"><font
                                                        style="color:#FF6600; font-weight:bold">合计:&nbsp;&nbsp;元</font>
                                                    </td>
                                                </tr>
                                            </table>
                                            <div style="text-align:right; margin-top:10px">
                                                <a
                                                    href="${pageContext.request.contextPath}/listProductByPage"><img
                                                    src="images/gwc_jx.gif" border="0" /> </a>
                                                &nbsp;&nbsp;&nbsp;&nbsp;<a href="#"><img
                                                    src="images/gwc_buy.gif" border="0" /> </a>
                                            </div></td>
                                    </tr>
                                </table></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>



    <jsp:include page="foot.jsp" />


</body>
</html>

servlet

public class AddProductToCartServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 1.得到id
        String id = request.getParameter("id");
        // 2.调用service中的根据id查询商品的方法
        ProductService service = new ProductService();

        try {
            Product p = service.findProductById(id);

            // 3.将商品添加到购物车
            // 3.1 从session中获取购物车
            Map<Product, Integer> cart = (Map<Product, Integer>) request
                    .getSession().getAttribute("cart");
            int count = 1; // 默认数据是1
            if (cart == null) { // 代表第一次购物,还没有购物车
                cart = new HashMap<Product, Integer>();
            } else {
                // 有购物车,需要考虑在购物车中有这个商品
                Integer c = cart.get(p);
                if (c != null) { // 说明购物车中有这个商品了
                    count = c + 1;
                }
            }
            cart.put(p, count); // 将商品添加到了购物车.

            // 4.将购物车存储到session中。
            request.getSession().setAttribute("cart", cart);

            response.getWriter()
                    .write("<a href='" + request.getContextPath()
                            + "/listProductByPage'>继续购物</a>,<a href='"
                            + request.getContextPath() + "/cart.jsp'>查看购物车</a>");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

service

public class ProductService {
    ProductDao dao = new ProductDao();

    // 添加商品
    public void addProduct(Product p) throws ProductException {

        try {
            dao.addProduct(p);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ProductException("添加商品失败");
        }
    }

    // 查询所有商品
    public List<Product> findAll() throws SQLException {
        return dao.findAll();
    }

    // 根据id查询商品
    public Product findProductById(String id) throws SQLException {
        return dao.findProductById(id);
    }

    // 修改商品
    public void editProduct(Product p) throws SQLException {
        dao.editProduct(p);
    }

    // 删除选中
    public void delSelectById(String[] ids) throws SQLException {
        dao.delSelectById(ids);
    }

    public List<Product> findByCondition(String id, String category,
            String name, String minPrice, String maxPrice) throws SQLException {

        return dao.findByCondition(id, category, name, minPrice, maxPrice);
    }

    // 分页显示数据
    // currentCount 每页条数
    // currentPage 当前页
    public PageBean findByPage(int currentCount, int currentPage)
            throws SQLException {
        // 1.求出总条数
        int totalCount = dao.findAllCount();
        // 2.求出总页数
        int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
        // 3.求出当前页的数据
        List<Product> ps = dao.findByPage(currentCount, currentPage);

        PageBean bean = new PageBean();
        bean.setTotalCount(totalCount);
        bean.setTotalPage(totalPage);
        bean.setCurrentCount(currentCount);
        bean.setCurrentPage(currentPage);
        bean.setPs(ps);
        
        return bean;
    }
}

 

 转载自: https://www.cnblogs.com/MessiAndDream/p/5882271.html

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值