目标:加入&查询购物车,清空购物车
一,购物车的三种实现方式:
2、cookie保存购物车(效率要更高、客户端、不安全)
3、数据库
注意:所有购物车相关的操作应该先登陆
购物车实体类创建
1、考虑结算功能,点击结算,需要将购物车的信息,分别传递到订单表以及订单项两张表对应的实体类
2、如果说一个页面要显示两张表的数据,要建立Vo类,Vo类中要包含两张对应的必要的列段元素
shoppingVo
1、点击添加购物车,会跳转到购物页面
2、随后要查询购物车的数据,也就是查询到session中的数据
将信息加入购物车:
点击添加传递到后台的是一个对象,然后购物车需要的是list集合进行显示
1、第一次添加购物车是没有数据的,也就意味着把vo放到list集合shopGoodsVos中,传递到前台即可
2、第二次添加到购物车,也就意味着之前有购物车相关信息
取出原有的购物车信息list 集合,将本次添加购物车的实体类vo放到原有的购物车信息list集合shopGoodsVos中
二,代码部分 实体类:
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;
子控制器action
public class ShoppingAction extends ActionSupport implements ModelDriver<ShoppingVo>{
ShoppingVo sv=new ShoppingVo();
@Override
public ShoppingVo getModel() {
// TODO Auto-generated method stub
return sv;
}
// 将商品信息加入到购物车
public String add(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
User cuser = (User) session.getAttribute("cuser");
ObjectMapper om=new ObjectMapper();
try {
if(cuser!=null) {
/*点击添加传递到后台的是一个对象,然后购物车需要的是list集合进行显示
1、第一次添加购物车中是没有数据的,也就意味着把vo放到list集合shopGoodsVos中,传递到前台即可
2、第二次添加到购物车,也就意味着之前有购物车相关信息,取出原有的购物车信息list集合,将本次添加购物车的实体类vo放到原有的购物车信息list集合中*/
long uid=cuser.getId();
List<ShoppingVo> shopGoodsVos=null;
// 从session取出当前用户对应的购物信息
String shoppingInfo=(String)session.getAttribute("shopping_"+uid);
if(StringUtils.isNotBlank(shoppingInfo)) {
// 第2/3次添加
// shoppingInfo包含了当前用户的购物车信息,也是通过list集合转成的一个json字符串
shopGoodsVos = om.readValue(shoppingInfo, List.class);
}else {
// 第1次添加
shopGoodsVos=new ArrayList<ShoppingVo>();
}
// vo指的是前台点击购物车具体商品内容
shopGoodsVos.add(sv);
session.setAttribute("shopping_"+uid, om.writeValueAsString(shopGoodsVos));
req.setAttribute("shopGoodsVos", shopGoodsVos);
}
}catch (Exception e){
e.printStackTrace();
}
return "shoppingCar";
}
}
购物车JS文件
<%@ 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">×</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>
mvc.xml配置
<action path="/shopping" type="com.dhm.web.ShoppingAction">
<forward name="shoppingCar" path="/fg/shoppingCar.jsp" redirect="false" />
</action>
效果展示:
二,清空购物车
子控制器:
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";
}
// 清空购物车
public void clear(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
User cuser = (User) session.getAttribute("cuser");
session.removeAttribute("shopping_"+cuser.getId());
try {
ResponseUtil.writeJson(resp, 1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}