版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/82733491
主要思路是点击加入购物车
在session创建购物车,加入product,num,和total
在购物车页面显示这些信息
并建立input value为 productid和num 列表
最后将这两个input,进入controller
1 购物车类
package com.ssh.po;
import java.util.List;
public class Cart {
private List<Product> products;//此处product的num属性不为卖家的总数量,而是买家买的数量
private float total;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
@Override
public String toString() {
return "Cart [products=" + products + ", total=" + total + "]";
}
}
2 点击加入购物车的do
<div class="btn_form" >
<form method="get"
action="${pageContext.request.contextPath}/buyer/addToCart.do">
<input type="hidden" value="${product.id }" name="productId">
<input type="submit" value="加入购物车" title="">
</form>
</div>
2 加入购物车的controller
@RequestMapping(value="/addToCart")
public ModelAndView addToCart(int productId,HttpServletRequest request){
HttpSession session=request.getSession();
Cart cart=(Cart)session.getAttribute("cart");
if(cart==null){
cart=new Cart();
cart.setTotal(0);
cart.setProducts(new ArrayList<Product>());
}
boolean hasProduct=false;
for (Product product : cart.getProducts()) {
if(product.getId()==productId){
hasProduct=true;
product.setNum(product.getNum()+1);
cart.setTotal(cart.getTotal()+product.getPrice());
break;
}
}
if(hasProduct==false){
Product product=buyerService.getProductById(productId);
product.setNum(1);
cart.getProducts().add(product);
cart.setTotal(cart.getTotal()+product.getPrice());
}
session.setAttribute("cart", cart);
List<Category> categories=buyerService.getAllCategory();
Product product=buyerService.getProductById(productId);
List<Product> remarkProduct=buyerService.getMaxRemarkProductsByCategoryId(product.getCategoryId());
ModelAndView modelAndView = new ModelAndView("/buyer/product_show");
modelAndView.addObject("categories", categories);
modelAndView.addObject("remarkProduct", remarkProduct);
modelAndView.addObject("product", product);
modelAndView.addObject("status", "success");
modelAndView.addObject("info", "加入购物车成功");
return modelAndView;
}
3 显示购物车的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>购物车</title>
<link href="${pageContext.request.contextPath}/conf3/css/bootstrap.css" rel='stylesheet' type='text/css' />
<script src="${pageContext.request.contextPath}/conf3/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/conf3/js/bootstrap.min.js"></script>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="${pageContext.request.contextPath}/conf3/js/jquery.min.js"></script>
<!-- Custom Theme files -->
<link href="${pageContext.request.contextPath}/conf3/css/style.css" rel='stylesheet' type='text/css' />
<!-- Custom Theme files -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!----webfonts---->
<link href='http://fonts.googleapis.com/css?family=Exo+2:100,200,300,400,500,600,700,800,900' rel='stylesheet' type='text/css'>
<link href="${pageContext.request.contextPath}/conf3/css/lanrenzhijia.css" rel="stylesheet" type="text/css" />
<script src="${pageContext.request.contextPath}/conf3/js/jquery.1.4.2-min.js"></script>
<script src="${pageContext.request.contextPath}/conf3/js/Calculation.js"></script>
<script>
$(document).ready(function () {
//jquery特效制作复选框全选反选取消(无插件)
// 所有复选(:checkbox)框点击事件
$(".gwc_tb2 input[name=newslist]").click(function () {
if ($(this).attr("checked")) {
//$(this).next().css({ "background-color": "#3366cc", "color": "#ffffff" });
} else {
// $(this).next().css({ "background-color": "#ffffff", "color": "#000000" });
}
});
// 输出
$(".gwc_tb2 input[name=newslist]").click(function () {
// $("#total2").html() = GetCount($(this));
GetCount();
//alert(conts);
});
});
//******************
function GetCount() {
var conts = 0;
var aa = 0;
$(".gwc_tb2 input[name=newslist]").each(function () {
if ($(this).attr("checked")) {
for (var i = 0; i < $(this).length; i++) {
conts += parseInt($(this).val());
aa += 1;
}
}
});
$("#shuliang").text(aa);
$("#zong1").html((conts).toFixed(2));
$("#jz1").css("display", "none");
$("#jz2").css("display", "block");
}
</script>
</head>
</script>
<%
if ((String)request.getAttribute("status") == "success") { %>
<script>
alert("${info}");
</script>
<%}%>
<body >
<%@ include file="header.jsp"%>
<div class="main">
<div class="container">
<div class="row content single" >
<%@ include file="side_product.jsp"%>
<div class="col-md-9">
<div class="breadcrumb">
<a href="${pageContext.request.contextPath}/buyer/index.do">首页</a>
>> <span class="last">购物车</span>
</div>
<div class="clearfix"> </div>
<div class="row content_bottom">
<form action="${pageContext.request.contextPath}/buyer/buyCart.do">
<div class="gwc" style=" margin:auto;">
<table cellpadding="0" cellspacing="0" class="gwc_tb1">
<tr>
<td class="tb1_td3">商品</td>
<td class="tb1_td4">卖家</td>
<td class="tb1_td5">数量</td>
<td class="tb1_td6">单价</td>
<!-- <td class="tb1_td7">操作</td> -->
</tr>
</table>
<!---商品加减算总数---->
<c:forEach items="${cart.products }" var="product" varStatus="status">
<script>
$(function () {
var t = $("#text_box${status.index}");
$("#add${status.index}").click(function () {
t.val(parseInt(t.val()) + 1)
setTotal(); GetCount();
})
$("#min${status.index}").click(function () {
t.val(parseInt(t.val()) - 1)
setTotal(); GetCount();
})
function setTotal() {
$("#total${status.index}").html((parseInt(t.val()) * '${product.price}').toFixed(2));
$("#newslist-${status.index}").val(parseInt(t.val()) * '${product.price}');
}
setTotal();
})
</script>
<table cellpadding="0" cellspacing="0" class="gwc_tb2">
<tr>
<td class="tb2_td1"><input type="checkbox" value="1" checked="checked" disabled="true" name="newslist" id="newslist-${status.index}" /></td>
<td class="tb2_td2"><a href="#"><img src="/product/${product.picPath }"/></a></td>
<td class="tb2_td3"><a href="#">${product.name }</a></td>
<td class="tb1_td4">${product.sellerName }</td>
<td class="tb1_td5"><input id="min${status.index}" name="" style=" width:20px; height:18px;border:1px solid #ccc;" type="button" value="-" />
<input type="hidden" value="${product.id }" name="productId"/>
<input id="text_box${status.index}" name="num" type="text" value="${product.num }" style=" width:30px; text-align:center; border:1px solid #ccc;" />
<input id="add${status.index}" name="" style=" width:20px; height:18px;border:1px solid #ccc;" type="button" value="+" />
</td>
<td class="tb1_td6"><label id="total${status.index}" class="tot" style="color:#ff5500;font-size:14px; font-weight:bold;"></label></td>
<!-- <td class="tb1_td7"><a href="#">删除</a></td> -->
</tr>
</table>
</c:forEach>
<!---总数---->
<script>
$(function () {
$(".quanxun").click(function () {
setTotal();
//alert($(lens[0]).text());
});
function setTotal() {
var len = $(".tot");
var num = 0;
for (var i = 0; i < len.length; i++) {
num = parseInt(num) + parseInt($(len[i]).text());
}
//alert(len.length);
$("#zong1").text(parseInt(num).toFixed(2));
$("#shuliang").text(len.length);
}
//setTotal();
})
</script>
<table cellpadding="0" cellspacing="0" class="gwc_tb3">
<td class="tb3_td2">已选商品
<label id="shuliang" style="color:#ff5500;font-size:14px; font-weight:bold;">0</label>
件</td>
<td class="tb3_td3">合计:<span>¥</span><span style=" color:#ff5500;">
<label id="zong1" style="color:#ff5500;font-size:14px; font-weight:bold;"></label>
</span></td>
<td class="tb3_td4"><span id="jz1">结算</span>
<input type="submit" style=" display:none;" class="jz2" id="jz2" value="结算"></td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<%@ include file="footer.jsp"%>
</body>
</html>
4 点击购买的controller
@RequestMapping(value="/buyCart")
public ModelAndView buyCart(int[] productId,int[] num,
HttpServletRequest request, RedirectAttributes redirectAttributes){
int length=productId.length;
int total=0;
List<Product> products=new ArrayList<Product>();
for(int i=0;i<length;i++){
Product now=buyerService.getProductById(productId[i]);
if(now.getNum()<num[i]){
List<Category> categories=buyerService.getAllCategory();
List<Product> remarkProduct=buyerService.getMaxRemarkProducts();
ModelAndView modelAndView = new ModelAndView("/buyer/cart_show");
modelAndView.addObject("categories", categories);
modelAndView.addObject("remarkProduct", remarkProduct);
modelAndView.addObject("status", "success");
modelAndView.addObject("info", now.getName()+"购买的数量太多");
return modelAndView;
}
products.add(now);
total=total+now.getPrice()*num[i];
}
if(total==0){
List<Category> categories=buyerService.getAllCategory();
List<Product> remarkProduct=buyerService.getMaxRemarkProducts();
ModelAndView modelAndView = new ModelAndView("/buyer/cart_show");
modelAndView.addObject("categories", categories);
modelAndView.addObject("remarkProduct", remarkProduct);
modelAndView.addObject("status", "success");
modelAndView.addObject("info", "用户没有购买东西");
return modelAndView;
}
HttpSession session=request.getSession();
Buyer buyer=(Buyer)session.getAttribute("buyer");
if(buyer.getMoney()<total){
List<Category> categories=buyerService.getAllCategory();
List<Product> remarkProduct=buyerService.getMaxRemarkProducts();
ModelAndView modelAndView = new ModelAndView("/buyer/cart_show");
modelAndView.addObject("categories", categories);
modelAndView.addObject("remarkProduct", remarkProduct);
modelAndView.addObject("status", "success");
modelAndView.addObject("info", "用户金钱不够");
return modelAndView;
}
Order order=new Order();
order.setBuyerId(buyer.getId());
order.setBuyerName(buyer.getName());
order.setTotalPrice(total);
buyerService.addOrder(order);
int orderId=order.getId();
for(int i=0;i<length;i++){
Product now=products.get(i);
if(num[i]==0){
continue;
}
DetailedOrder detailedOrder=new DetailedOrder();
detailedOrder.setOrderId(orderId);
detailedOrder.setProductId(now.getId());
detailedOrder.setProductName(now.getName());
detailedOrder.setBuyerId(buyer.getId());
detailedOrder.setBuyerName(buyer.getName());
detailedOrder.setSellerId(now.getSellerId());
detailedOrder.setSellerName(now.getSellerName());
detailedOrder.setPrice(now.getPrice());
detailedOrder.setNum(num[i]);
buyerService.addDetailedOrder(detailedOrder);
}
session.removeAttribute("cart");
List<Category> categories=buyerService.getAllCategory();
List<Product> remarkProduct=buyerService.getMaxRemarkProducts();
ModelAndView modelAndView = new ModelAndView("/buyer/cart_show");
modelAndView.addObject("categories", categories);
modelAndView.addObject("remarkProduct", remarkProduct);
modelAndView.addObject("status", "success");
modelAndView.addObject("info", "购买成功");
return modelAndView;
}