网上书城的购物车功能(下)
程序员文章站
2022-04-19 13:30:28
购物车功能前言所需要的拦截器辅助类,web包拦截器辅助类web包购物车(拦截器,查询功能,删除功能,更新功能)多个功能代码效果图下单结算功能css样式前言本次我们学习购物车功能中的拦截器,查询功能,删除功能,更新功能,下单结算功能等这多个功能所需要的拦截器辅助类,web包拦截器辅助类ShoppingFilter 在要把商品加入购物车的时候需要先登录,才能把商品加入购物车package com.tang.filter;import javax.servlet.*;import javax....
前言
本次我们学习购物车功能中的拦截器,查询功能,删除功能,更新功能,下单结算功能等这多个功能
所需要的拦截器辅助类,web包
拦截器辅助类
ShoppingFilter 在要把商品加入购物车的时候需要先登录,才能把商品加入购物车
package com.tang.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tang.entity.User;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 除去login.jsp、register.jsp、index.jsp、、/static/*、/user.action
*/
@WebFilter(filterName = "urlFiter",urlPatterns = "/*")
public class ShoppingFilter implements Filter {
public ShoppingFilter(){
super();
}
// 只要以下urls是不需要session的
private boolean validateUrl(String uri){
boolean flag = true;
String[] urls = new String[]{"login.jsp","register.jsp","ndex.jsp","static","user.action","category.action","book.action"};
for (String url : urls) {
if (uri.contains(url)){
flag = false;
break;
}
}
return flag;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 这些请求路径之外都要登录后才能访问
String uri = req.getRequestURI();
if((!"/".equals(uri)) && validateUrl(uri)) {
;String methodName = req.getParameter("methodName");
// if ("add".equals(methodName) || "pay".equals(methodName) || "list".equals(methodName)){
User user = (User) req.getSession().getAttribute("currentUser");
if(user == null){
resp.sendRedirect("/login.jsp");
return;
}
// }
}
chain.doFilter(request, response);
}
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
web包
ShoppingAction (购物列表查询, 清空购物车, 删除购物车, 购物车结算)
package com.tang.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tang.dao.OrderDao;
import com.tang.dao.OrderItemDao;
import com.tang.entity.Order;
import com.tang.entity.OrderItem;
import com.tang.entity.User;
import com.tang.util.EasyuiResult;
import com.tang.util.ResponseUtil;
import com.tang.util.StringUtils;
import com.tang.vo.ShopGoodsVo;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;
public class ShoppingAction extends ActionSupport implements ModelDriven<ShopGoodsVo>{
private ShopGoodsVo shopGoodsVo = new ShopGoodsVo();
private OrderDao orderDao = new OrderDao();
private OrderItemDao orderItemDao = new OrderItemDao();
// 加入购物车
public String add(HttpServletRequest request, HttpServletResponse response) {
ObjectMapper om = new ObjectMapper();
User currentUser = (User) request.getSession().getAttribute("currentUser");
long uid = currentUser.getId();
String shopId = "shopId_" + uid;
String shopVo = (String) request.getServletContext().getAttribute(shopId);
List<ShopGoodsVo> shopGoodsVos = null;
try {
if (StringUtils.isNotBlank(shopVo)) {
// 购物车没有数据处理逻辑
shopGoodsVos = (List<ShopGoodsVo>) om.readValue(shopVo, List.class);
shopGoodsVos.add(shopGoodsVo);
} else {
// 购物车有数据处理逻辑
shopGoodsVos = new ArrayList<>();
shopGoodsVos.add(shopGoodsVo);
} request.getServletContext().setAttribute(shopId,om.writeValueAsString(shopGoodsVos));
request.setAttribute("shopGoodsVos",shopGoodsVos);
} catch (IOException e) {
e.printStackTrace();
}
return "shoppingCar";
}
// 购物列表查询
public String list(HttpServletRequest request, HttpServletResponse response) {
ObjectMapper om = new ObjectMapper();
try {
User currentUser = (User) request.getSession().getAttribute("currentUser");
long uid = currentUser.getId();
String shopId = "shopId_" + uid;
String shopVoStr = (String) request.getServletContext().getAttribute(shopId);
List<ShopGoodsVo> shopGoodsVos = null;
if (StringUtils.isNotBlank(shopVoStr)){
shopGoodsVos = om.readValue(shopVoStr, List.class);
}else
{
shopGoodsVos = new ArrayList<>();
}
request.setAttribute("shopGoodsVos",shopGoodsVos);
} catch (IOException e) {
e.printStackTrace();
}
return "shoppingCar";
}
// 清空购物车
public String clear(HttpServletRequest request, HttpServletResponse response) {
User currentUser = (User) request.getSession().getAttribute("currentUser");
long uid = currentUser.getId();
String shopId = "shopId_" + uid;
request.getServletContext().removeAttribute(shopId);
try {
ResponseUtil.writeJson(response, EasyuiResult.SUCCESS);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 删除购物车
public String del(HttpServletRequest request, HttpServletResponse response) {
ObjectMapper om = new ObjectMapper();
try {
User currentUser = (User) request.getSession().getAttribute("currentUser");
long uid = currentUser.getId();
String shopId = "shopId_" + uid;
String shopVoStr = (String) request.getServletContext().getAttribute(shopId);
List<ShopGoodsVo> shopGoodsVos = om.readValue(shopVoStr, List.class);
int index = Integer.valueOf(shopGoodsVo.getPageStr());
shopGoodsVos.remove(index);
request.getServletContext().setAttribute(shopId,om.writeValueAsString(shopGoodsVos));
} catch (Exception e) {
e.printStackTrace();
}
return list(request,response);
}
// 购物车结算
public String createOrder(HttpServletRequest request, HttpServletResponse response) {
try {
User currentUser = (User) request.getSession().getAttribute("currentUser");
long uid = currentUser.getId();
/*
ShopGoodsVo(name=null, price=0.0, num=0, total=0.0, consignee=8, phone=8, postalcode=8, address=8, sendType=1,
pageStr=,斗破苍穹-0.0-1-66.0,时光走了你还在-0.0-1-33.0,测试-0.0-1-3.0)
*/
String pageStr = shopGoodsVo.getPageStr();
float total = 0;
List<OrderItem> orderItems = new ArrayList<>();
OrderItem orderItem = null;
// 订单项就暂时不做了
for (String s : pageStr.substring(1).split(",")) {
orderItem = new OrderItem();
String[] items = s.split("-");
orderItem.setBid(items[0]);
orderItem.setQuantity(Integer.valueOf(items[2]));
total += Float.valueOf(items[items.length-1]);
orderItems.add(orderItem);
}
// System.out.println(shopGoodsVo);
Order order = new Order();
order.setAddress(shopGoodsVo.getAddress());
order.setConsignee(shopGoodsVo.getConsignee());
order.setOrderPrice(total);
order.setOrderState(1);
order.setPhone(shopGoodsVo.getPhone());
order.setPostalcode(shopGoodsVo.getPostalcode());
order.setSendType(shopGoodsVo.getSendType());
order.setUid(uid);
int res = this.orderDao.add(order);
// 按订单生成时间倒序获取新生成订单的id
Order newest = this.orderDao.newest();
// 然后for入订单项库
for (OrderItem item : orderItems) {
item.setOid(newest.getId());
this.orderItemDao.add(item);
}
ResponseUtil.writeJson(response, res);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public ShopGoodsVo getModel() {
return shopGoodsVo;
}
}
购物车(拦截器,查询功能,删除功能,更新功能)多个功能代码
ShoppingCar.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>购物车</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/css/fg.css" />
</head>
<body>
<div class="container">
<!-- 横幅 -->
<div class="row">
<div class="col-sm-4">
您好,欢迎来到网上书城!
</div>
<div class="col-sm-4 col-sm-offset-4">
<a href="#">登录</a> | <a href="#">注册</a> | <b>我的购物车</b> | <i>网站首页</i>
</div>
</div>
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button type="button" class="btn btn-primary">搜索</button>
</div>
</div>
<!-- 主内容区 -->
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category ">
<li class="list-group-item" style="color: white;">书籍分类</li>
</ul>
</div>
<div class="col-sm-9">
<table class="table">
<thead class="thead-dark">
<tr style="background-color: papayawhip;">
<th scope="col">书名</th>
<th scope="col">单价</th>
<th scope="col">数量</th>
<th scope="col">小计</th>
<th scope="col">操作</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>
<td colspan="5">
<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>
</div>
</div>
<!-- 底部版权 -->
<div class="row">
<div class="col-sm-12 text-center">
Copyright 2020 教育,版权所有
</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<script src="${pageContext.request.contextPath}/static/js/common.js"></script>
<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';
}
});
}
})
}
</script>
</body>
</html>
效果图
更新
删除
清空
在你点击清空购物车的时候,会有一个弹出框,弹出您确认想要清空购物车吗?,点击确定所有的商品被清空
下单结算功能
点击结算弹出
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>购物车</title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/css/fg.css" />
</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>
<!-- 横幅 -->
<div class="row">
<div class="col-sm-4">
您好,欢迎来到网上书城!
</div>
<div class="col-sm-4 col-sm-offset-4">
<a href="#">登录</a> | <a href="#">注册</a> | <b>我的购物车</b> | <i>网站首页</i>
</div>
</div>
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button type="button" class="btn btn-primary">搜索</button>
</div>
</div>
<!-- 主内容区 -->
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category ">
<li class="list-group-item" style="color: white;">书籍分类</li>
</ul>
</div>
<div class="col-sm-9">
<table class="table">
<thead class="thead-dark">
<tr style="background-color: papayawhip;">
<th scope="col">书名</th>
<th scope="col">单价</th>
<th scope="col">数量</th>
<th scope="col">小计</th>
<th scope="col">操作</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>
<td colspan="5">
<button type="button" onclick="clearCar();" class="btn bg-orange2" style="width: 200px;">清空购物车</button>
<button type="button" class="btn bg-orange2" style="width: 200px;" onclick="javascript:history.back();">继续购买</button>
<button type="button" class="btn btn-danger car_pay" style="width: 200px;">去结算</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 底部版权 -->
<div class="row">
<div class="col-sm-12 text-center">
Copyright 2020 教育,版权所有
</div>
</div>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<script src="${pageContext.request.contextPath}/static/js/common.js"></script>
<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() {
debugger;
$.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>
css样式
fg.css
在添加这几个样式
.bg-orange{
background-color: #FF0606 ;
}
.bg-orange2{
background-color: #FF0606 ;
}
/* 购物车弹出框 */
.shop-modal{
position: absolute;
width: 600px;
/* height: 800px; */
left: 50%;
top: 100px;
margin-left: -200px;
z-index: 2;
}
.shop-modal input{
padding-left: 20px;
width: 100%;
}
本文地址:https://blog.csdn.net/TZyybhs/article/details/107279430