EasyUI项目之购物车功能

一、目标:

1、加入购物 2、查询购物车 3、清空购物车

二、实现购物的三种方式:
第一种:session 保存购物车信息到session

1.点击我的购物车,查询后台的seesion,通过用户账号去查找

2.如果有那就显示,如果没有就不显示

3.添加购物车,将数据加入两个地方;前台html显示,后台的session通过userid进行保存sessi内容

4.清空购物车,清空session 

注意:所有购物车相关的操作应该先登录!

第二种:cookie保存购物车 效率要更高

第三种:数据库

三、加入购物车

首先看书籍界面:findbook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <meta charset="utf-8">
    <title>网上书城首页</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/css/fg.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/index.js"></script>
</head>
<body class="text-center">
<div class="container">
    <div class="row head">
        <div class="col-md-12">
            <i>
                您好,欢迎来到飞凡网上书店!
            </i>
            <b>
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/login.jsp">登录</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/register.jsp">注册</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/Shopping.action?methodName=list">我的购物车</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/">网站首页</a>
            </b>
        </div>
    </div>
    <!-- 横幅搜索栏 start -->
    <div class="row banner">
        <div class="img1"></div>
        <div class="col-md-12">
            <form class="form" action="${pageContext.request.contextPath}/book.action?methodName=findByName" method="post">
                <%--<input type="hidden" name="methodName" value="findByName">--%>
                <input type="text" name="name" value="" id="input" class="search">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>
    <!-- 横幅搜索栏 end -->
    <!-- 页面主体内容 start -->
    <div class="row content">
        <div class="col-md-3 float-left c-left">
            <ul class="list-group">
                <li class="list-group-item">书籍分类</li>
            </ul>
        </div>
        <%--${books}--%>
        <div class="col-md-9 float-right c-right">
            <c:forEach var="b" items="${books}">
                <div class="media">
                    <img style="width: 100px;height: 140px;" src="${pageContext.request.contextPath}${b.image}" class="align-self-center mr-3" alt="...">
                    <div class="media-body text-left">
                        <p>${b.name}</p>
                        <p>作者:${b.author}</p>
                        <p>价格:${b.price}</p>
                        <p>出版社:${b.publishing}</p>
                        <p>书籍简介:${b.description}</p>
                        <span>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/Shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/Shopping.action?methodName=pay">去结算</a>
							</span>
                    </div>
                </div>
                <hr>
            </c:forEach>
 
            <%--<div class="media">--%>
            <%--<img src="imgs/2.png" class="align-self-center mr-3" alt="...">--%>
            <%--<div class="media-body text-left">--%>
            <%--<p>第一商会</p>--%>
            <%--<p>作者:寒川子</p>--%>
            <%--<p>价格:¥24.80</p>--%>
            <%--<p>出版社:北京联合出版公司</p>--%>
            <%--<p>书籍简介:超级畅销书作家寒川子创作历时三年全新力作!讲述财富与权力“离不开,靠不住”的明暗法则</p>--%>
            <%--<span>--%>
            <%--<button type="button" class="btn btn-danger">加入购物车</button>--%>
            <%--<button type="button" class="btn btn-danger">去结算</button>--%>
            <%--</span>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<hr>--%>
 
            <xl:page pageBean="${pageBean}"></xl:page>
        </div>
    </div>
    <!-- 页面主体内容 end -->
    <!-- 网站版权 start -->
    <div class="row footer">
        <div class="col-md-12">
            Copyright ©2014 飞凡教育,版权所有
        </div>
    </div>
    <!-- 网站版权 end -->
</div>
<script type="text/javascript">
    function searchByType(cid){
        location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
    };
</script>
 
</body>
</html>

1.购物车实体类

package com.zking.vo;
 
public class ShoppingVo {
   //购物车列表订单所需数据
	private String name;
	private float price;
	private int num;
	private float total;
	
	//提交订单所需数据
	private String consignee;
	private String phone;
	private String postalcode;
	private String address;
	private int sendType;
	
	//页面的所有传参字符串
	private String pageStr;
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public float getPrice() {
		return price;
	}
 
	public void setPrice(float price) {
		this.price = price;
	}
 
	public int getNum() {
		return num;
	}
 
	public void setNum(int num) {
		this.num = num;
	}
 
	public float getTotal() {
		return total;
	}
 
	public void setTotal(float total) {
		this.total = total;
	}
 
	public String getConsignee() {
		return consignee;
	}
 
	public void setConsignee(String consignee) {
		this.consignee = consignee;
	}
 
	public String getPhone() {
		return phone;
	}
 
	public void setPhone(String phone) {
		this.phone = phone;
	}
 
	public String getPostalcode() {
		return postalcode;
	}
 
	public void setPostalcode(String postalcode) {
		this.postalcode = postalcode;
	}
 
	public String getAddress() {
		return address;
	}
 
	public void setAddress(String address) {
		this.address = address;
	}
 
	public int getSendType() {
		return sendType;
	}
 
	public void setSendType(int sendType) {
		this.sendType = sendType;
	}
 
	public String getPageStr() {
		return pageStr;
	}
 
	public void setPageStr(String pageStr) {
		this.pageStr = pageStr;
	}
 
	@Override
	public String toString() {
		return "ShoppingVo [name=" + name + ", price=" + price + ", num=" + num + ", total=" + total + ", consignee="
				+ consignee + ", phone=" + phone + ", postalcode=" + postalcode + ", address=" + address + ", sendType="
				+ sendType + ", pageStr=" + pageStr + "]";
	}
	
	
}

2.购物车没有相应的数据库表,所以没有dao类

3.子控制器ShoppingAction 写增加的方法

1.点击添加购物车,会跳转到购物车界面

2.随后要查询购物车的数据,也就是查询session中的数据

public class ShoppingAction extends ActionSupport implements ModelDriver<ShoppingVo>{
    private ShoppingVo vo=new ShoppingVo();
	
	public ShoppingVo getModel() {
		return vo;
	}
 
    /**
     * 将信息加入购物车
     * @param req
     * @param resp
     * @return
     */
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		HttpSession session=req.getSession();
		User cuser=(User) session.getAttribute("cuser");
		//System.out.println(cuser);
		ObjectMapper om=new ObjectMapper();
		try {
			if(cuser!=null) {
				/*
				 *点击添加传递到后台的是一个对象,然后购物车需要的是list集合进行显示
				 *1.第一次添加购物车中是没有数据的,也就意味着把vo放到list集合shopGoodsVo
				 *2.第二次添加到购物车,也就意味着之前有购物车相关信息
				 *取出原有的购物车信息list集合,将本次添加购物车的实体类vo放到原有的购物车信息list中
				 */
				long uid=cuser.getId();
				List<ShoppingVo> shopGoodsVos=null;
				//从session取出当前用户对应的购物车信息
				String shoppingInfo=(String) session.getAttribute("shopping_"+uid);
				//System.out.println(shoppingInfo);
				if(StringUtils.isNotBlank(shoppingInfo)) {
				//第2/3次	添加
				//shoppingInfo包含了当前用户的购物车信息	,也是通过list集合转成的一个Json字符串
					shopGoodsVos=om.readValue(shoppingInfo,List.class);
					
				}else {
			    //第1次添加	
					shopGoodsVos=new ArrayList<ShoppingVo>();
				}
				//vo指的是前台点击购物车具体商品内容
				shopGoodsVos.add(vo);
				System.out.println(shopGoodsVos);
				session.setAttribute("shopping_"+uid,om.writeValueAsString(shopGoodsVos));
	            req.setAttribute("shopGoodsVos",shopGoodsVos);
	            //System.out.println(222);
	           // req.getRequestDispatcher("/fg/shoppingCar.jsp").forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println(66);
		return "shoppingCar";
		
	}

4.mvc文件的配置

  <action type="com.zxy.web.ShoppingAction" path="/Shopping">
<forward path="/fg/shoppingCar.jsp" redirect="false" name="shoppingCar"/>
</action>

 效果:

EasyUI项目之购物车功能

 

 四、查询购物车

shoppingAction

public String list(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User cuser = (User) session.getAttribute("cuser");
        ObjectMapper om=new ObjectMapper();
//        查询当前用户的购物信息
        String shoppingInfo= (String) session.getAttribute("shopping_"+cuser.getId());
        try {
            List<ShoppingVo> shopGoodsVos=om.readValue(shoppingInfo, List.class);
            req.setAttribute("shopGoodsVos", shopGoodsVos);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "shoppingCar";
    }

点击加入购物车后的效果:

EasyUI项目之购物车功能

 五、清空购物车

shoppingAction

//    清空购物车
    public void clear(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        User cuser = (User) session.getAttribute("cuser");
        System.out.println(33);
        session.removeAttribute("shopping_"+cuser.getId());
        try {
            ResponseUtil.writeJson(resp, 1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
	

ShoppingCar.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <meta charset="utf-8">
    <title>购物车</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css"
          href="${pageContext.request.contextPath}/static/js/easyui/themes/default/easyui.css">
    <link href="${pageContext.request.contextPath}/static/css/fg.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/static/js/easyui/jquery.easyui.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/index.js"></script>
</head>
<body class="text-center">
<div class="container">
 
    <!-- 购物车新增模态框 -->
    <div class="shop-modal modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">订单信息</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form class="shop-form" method="post">
                        <div class="row">
                            <!-- <div class="col-md-3">收货人:</div> -->
                            <div class="col-md-12"><input type="text" name="consignee" id="consignee" placeholder="收货人"
                                                          value=""/></div>
                        </div>
                        <div class="row">
                            <!-- <div class="col-md-3">手机号:</div> -->
                            <div class="col-md-12"><input type="text" name="phone" placeholder="收货人手机号" id="phone"
                                                          value=""/></div>
                        </div>
                        <div class="row">
                            <!-- <div class="col-md-3">收货人邮编:</div> -->
                            <div class="col-md-12"><input type="text" name="postalcode" placeholder="收货人邮编"
                                                          id="postalcode" value=""/></div>
                        </div>
                        <div class="row">
                            <!-- <div class="col-md-3">收货地址:</div> -->
                            <div class="col-md-12"><input type="text" name="address" placeholder="收货地址" id="address"
                                                          value=""/></div>
                        </div>
                        <div class="row">
                            <!-- <div class="col-md-3">发货方式</div> -->
                            <div class="col-md-12">
                                <select class="form-control" name="sendType" id="sendType">
                                    <option value="1">平邮</option>
                                    <option value="2">快递</option>
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary order_Create">确定</button>
                </div>
            </div>
        </div>
    </div>
 
    <div class="row head">
        <div class="col-md-12">
            <i>
                您好,欢迎来到飞凡网上书店!
            </i>
            <b>
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/login.jsp">登录</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/register.jsp">注册</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/shopping.action?methodName=list">我的购物车</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/">网站首页</a>
            </b>
        </div>
    </div>
    <!-- 横幅搜索栏 start -->
    <div class="row banner">
        <div class="img1"></div>
        <div class="col-md-12">
            <form class="form" action="${pageContext.request.contextPath}/book.action?methodName=findByName" method="post">
                <%--<input type="hidden" name="methodName" value="findByName">--%>
                <input type="text" name="name" value="" id="input" class="search">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>
    <!-- 横幅搜索栏 end -->
    <!-- 页面主体内容 start -->
    <div class="row content">
        <div class="col-md-3 float-left c-left">
            <ul class="list-group">
                <li class="list-group-item">书籍分类</li>
            </ul>
        </div>
        <%--${books}--%>
        <div class="col-md-9 float-right c-right">
 
            <table class="table table-striped">
                <thead class="list-group-item-hover">
                <tr>
                    <%--<th>编号</th>--%>
                    <th>书名</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="s" items="${shopGoodsVos}" varStatus="index">
                    <tr>
                            <%--<th>${index.index}</th>--%>
                        <th>${s.name}</th>
                        <td>${s.price}</td>
                        <td>
                            <input type="text" class="text-center item_num" name="num" value="${s.num}"/>
                        </td>
                        <td>${s.total}</td>
                        <td>
                                <%--<a href="#" class="text-primary" onclick="shopingDel(${s.name},${s.price},${s.num},${s.total})">删除</a>--%>
                            <a href="${pageContext.request.contextPath}/shopping.action?methodName=del&pageStr=${index.index}"
                               class="text-primary">删除</a>
                            <a href="#" class="text-primary" onclick="sshopUpdate(this);">更新</a>
                        </td>
                    </tr>
                </c:forEach>
 
                <tr class="bg-white">
                    <td colspan="5" class="text-center">
                        <button type="button" onclick="clearCar();" class="btn bg-orange2">清空购物车</button>
                        <button type="button" class="btn bg-orange2 continue-buy">继续购买</button>
                        <button type="button" class="btn btn-danger car_pay">去结算</button>
                    </td>
                </tr>
                </tbody>
            </table>
            <%--<xl:page pageBean="${pageBean}"></xl:page>--%>
        </div>
    </div>
    <!-- 页面主体内容 end -->
    <!-- 网站版权 start -->
    <div class="row footer">
        <div class="col-md-12">
            Copyright ©2014 飞凡教育,版权所有
        </div>
    </div>
    <!-- 网站版权 end -->
</div>
<script type="text/javascript">
    <%--跟新购物车--%>
 
    function sshopUpdate(ele) {
        // console.log($(ele).parent().parent());
        var $parent = $(ele).parent().parent();
        var $price_td = $parent.children().eq(1);
        var $num_td = $parent.children().eq(2);
        var $total_td = $parent.children().eq(3);
 
        var price = $price_td.html();
        var num = $num_td.find(":input").val();
        var total = parseInt(num) * parseFloat(price);
        $total_td.html(parseFloat(total).toFixed(1));
    }
 
    <%--书籍搜索功能--%>
 
    function searchByType(cid) {
        location.href = '${pageContext.request.contextPath}/book.action?methodName=findByType&cid=' + cid;
    };
 
    //清除购物车
    function clearCar() {
        $.messager.confirm('确认', '您确认想要清空购物车吗?', function (r) {
            if (r) {
                $.ajax({
                    url: '${pageContext.request.contextPath}/shopping.action?methodName=clear',
                    success: function (data) {
                        location.href = '${pageContext.request.contextPath}/shopping.action?methodName=list';
                    }
                });
            }
        })
    }
 
    $(function () {
        // 给模态框添加关闭事件
        $('.close span,.modal-footer .btn-secondary').click(function () {
            $('.shop-modal').addClass('modal');
        })
        // 购物车结算
        $(".car_pay").click(function () {
            $('.shop-modal').removeClass('modal');
        })
 
        $(".order_Create").click(function () {
            var consignee = $("#consignee").val();
            var phone = $("#phone").val();
            var postalcode = $("#postalcode").val();
            var address = $("#address").val();
            var sendType = $("#sendType").val();
            var single_tr = "";
            $(".table tr:gt(0)").not(":last").each(function (index, node) {
                console.log(index);
                single_tr = single_tr + "," + $(this).find("th").eq(0).html() + "-" + $(this).find("td").eq(0).html() + "-"
                    + $(this).find("td").eq(1).find("input").val() + "-" + $(this).find("td").eq(2).html();
            })
            console.log(single_tr.substring(1));
 
            var param = "consignee=" + consignee + "&phone=" + phone + "&postalcode=" + postalcode + "&address=" + address + "&sendType=" + sendType + "&pageStr=" + single_tr;
 
            $.ajax({
                url: '${pageContext.request.contextPath}/shopping.action?methodName=createOrder',
                type: "POST",
                data: param,
                success: function (data) {
                    var consignee = $("#consignee").val("");
                    var phone = $("#phone").val("");
                    var postalcode = $("#postalcode").val("");
                    var address = $("#address").val("");
                    var sendType = $("#sendType").val("");
                    $('.shop-modal').addClass('modal');
                    $(".table tr:gt(0)").not(":last").remove();
                    $.ajax({
                        url: '${pageContext.request.contextPath}/shopping.action?methodName=clear',
                        success: function (data) {
                            <%--location.href = '${pageContext.request.contextPath}/shopping.action?methodName=list';--%>
                        }
                    });
                }
            });
        });
 
    })
</script>
 
</body>
</html>

最终效果:

EasyUI项目之购物车功能

点击清空购物车之后的效果展示图:

EasyUI项目之购物车功能

 

 结束lalala~~~~~

上一篇:数据结构与算法—双端队列的实现


下一篇:Easyui项目:门户书籍类别查询以及图片上传