新峰商城之购物车(二)

        购物车中列表功能,也是购物车的一个重要功能,购物车页面的商品列表是一个List对象和一些总览性字段。以下主要讲述购物车列表功能的主要实现步骤和代码。

一、数据格式的定义

        购物项列表数据中的商品标题字段、商品预览图字段、商品价格字段可以通过购物项表中的goods_id 来关联和查询,而其商品数量字段通过购物项表来查询,列表还有一个删除按钮,因此需要返回购物项的id字段。总览性数据包括加购总量字段和总价字段。返回数据的格式为购物项列表数据+加购总量字段+总价字段。购物项VO对象编码如下所示:

public class NewBeeMallShoppingCartItemVO implements Serializable {private Long cartItemId;private Long goodsId;private Integer goodsCount;private String goodsName;private String goodsCoverImg;private Integer sellingPrice;}

二、购物车列表数据的获取

购物车列表中的字段可以分别通过查询shopping_cart_item购物项表和goods_info商品表获取。

实体层

(1)Mapper接口

首先在购物项实体Mapper接口的NewBeeMallShoppingCartItemMapper.java中增加如下方法:

//根据userId和number字段获取固定数量的购物项列表数据List<NewBeeMallShoppingCartItem> selectByUserId(@Param("newBeeMallUserId") Long newBeeMallUserId, @Param("number") int number);

(2)Mapper映射文件

映射文件NewBeeMallShoppingCartItemMapper.xml添加具体的SQL语句,代码如下:

<select id="selectByUserId" resultMap="BaseResultMap">select<include refid="Base_Column_List"/>from tb_newbee_mall_shopping_cart_itemwhere user_id = #{newBeeMallUserId,jdbcType=BIGINT} and is_deleted = 0limit #{number}
</select>

业务层

在业务类中增加getMyShoppingCartItems方法,用以获取购物项列表数据,

在NewBeeMallShoppingCartService.java中增加方法,主要代码如下:

//获取我的购物车中的列表数据
List<NewBeeMallShoppingCartItemVO> getMyShoppingCartItems(Long newBeeMallUserId);

在NewBeeMallShoppingCartServiceImpl类中实现方法,主要代码如下:

 @Overridepublic List<NewBeeMallShoppingCartItemVO> getMyShoppingCartItems(Long newBeeMallUserId) {List<NewBeeMallShoppingCartItemVO> newBeeMallShoppingCartItemVOS = new ArrayList<>();List<NewBeeMallShoppingCartItem> newBeeMallShoppingCartItems = newBeeMallShoppingCartItemMapper.selectByUserId(newBeeMallUserId, Constants.SHOPPING_CART_ITEM_TOTAL_NUMBER);if (!CollectionUtils.isEmpty(newBeeMallShoppingCartItems)) {//查询商品信息并做数据转换List<Long> newBeeMallGoodsIds = newBeeMallShoppingCartItems.stream().map(NewBeeMallShoppingCartItem::getGoodsId).collect(Collectors.toList());List<NewBeeMallGoods> newBeeMallGoods = newBeeMallGoodsMapper.selectByPrimaryKeys(newBeeMallGoodsIds);Map<Long, NewBeeMallGoods> newBeeMallGoodsMap = new HashMap<>();if (!CollectionUtils.isEmpty(newBeeMallGoods)) {newBeeMallGoodsMap = newBeeMallGoods.stream().collect(Collectors.toMap(NewBeeMallGoods::getGoodsId, Function.identity(), (entity1, entity2) -> entity1));}for (NewBeeMallShoppingCartItem newBeeMallShoppingCartItem : newBeeMallShoppingCartItems) {NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO = new NewBeeMallShoppingCartItemVO();BeanUtil.copyProperties(newBeeMallShoppingCartItem, newBeeMallShoppingCartItemVO);if (newBeeMallGoodsMap.containsKey(newBeeMallShoppingCartItem.getGoodsId())) {NewBeeMallGoods newBeeMallGoodsTemp = newBeeMallGoodsMap.get(newBeeMallShoppingCartItem.getGoodsId());newBeeMallShoppingCartItemVO.setGoodsCoverImg(newBeeMallGoodsTemp.getGoodsCoverImg());String goodsName = newBeeMallGoodsTemp.getGoodsName();// 字符串过长导致文字超出的问题if (goodsName.length() > 28) {goodsName = goodsName.substring(0, 28) + "...";}newBeeMallShoppingCartItemVO.setGoodsName(goodsName);newBeeMallShoppingCartItemVO.setSellingPrice(newBeeMallGoodsTemp.getSellingPrice());newBeeMallShoppingCartItemVOS.add(newBeeMallShoppingCartItemVO);}}}return newBeeMallShoppingCartItemVOS;}

代码通过传入userid字段作为参数,然后通过SQL查询出当前userid下的购物项列表数据。因为购物车页面需要展示商品信息,所以通过购物项表中的goods_id 获取每个购物项对应的商品信息。接着填充数据,即将相关字段封装到NewBeeMallShoppingCartItemVO对象中。

三、购物车列表数据的渲染

控制层

数据最终通过Thymeleaf语法渲染到前端页面上,首先需要将获取的数据转发到对应模板页面中,就必须在Controller层方法中将查询到的数据放入request请求中。

ShoppingCartController中新增cartListPage()方法,代码如下:

@GetMapping("/shop-cart")public String cartListPage(HttpServletRequest request,HttpSession httpSession) {NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);int itemsTotal = 0;int priceTotal = 0;List<NewBeeMallShoppingCartItemVO> myShoppingCartItems = newBeeMallShoppingCartService.getMyShoppingCartItems(user.getUserId());if (!CollectionUtils.isEmpty(myShoppingCartItems)) {//购物项总数itemsTotal = myShoppingCartItems.stream().mapToInt(NewBeeMallShoppingCartItemVO::getGoodsCount).sum();if (itemsTotal < 1) {NewBeeMallException.fail("购物项不能为空");}//总价for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : myShoppingCartItems) {priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();}if (priceTotal < 1) {NewBeeMallException.fail("购物项价格异常");}}request.setAttribute("itemsTotal", itemsTotal);request.setAttribute("priceTotal", priceTotal);request.setAttribute("myShoppingCartItems", myShoppingCartItems);return "mall/cart";}

 在代码中首先调用业务层的方法,把当前用户添加到购物车中的购物项数据全部读取出来,然后计算商品总数和总价,并将三个对象都放到request对象中,最后跳转到mall目录下的cart.html模板页面进行数据渲染。

前端

在resource/templates/mall目录中增加cart.html,模板代码如下所示:

<!-- Copyright (c) 2019-2020 十三 all rights reserved. -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>NewBee商城-购物车</title><link rel="stylesheet" th:href="@{mall/css/iconfont.css}"><link rel="stylesheet" th:href="@{mall/css/common.css}"><link rel="stylesheet" th:href="@{mall/styles/header.css}"><link rel="stylesheet" th:href="@{mall/styles/cart.css}"><link rel="stylesheet" th:href="@{/admin/plugins/sweetalert2/sweetalert2.min.css}"/>
</head>
<body><div id="cart"><div class="banner_x center"><a th:href="@{/index}" target="_blank"><div class="logo fl"><img src="mall/image/new-bee-logo-3.png"/></div></a><div class="wdgwc fl ml20">购物车</div><div class="wxts fl ml20">温馨提示:产品是否购买成功,以最终下单为准哦,请尽快结算</div><div class="clear"></div></div><div class="cart_line"></div><div class="cart_bg"><th:block th:if="${#lists.isEmpty(myShoppingCartItems)}"><div class="list center"><img style="position: absolute;margin-top: 16px;left: 45%;" th:src="@{/mall/image/null-content.png}"></div></th:block><th:block th:unless="${#lists.isEmpty(myShoppingCartItems)}"><div class="list center"><div class="top2 center"><div class="sub_top fl"></div><div class="sub_top fl">商品名称</div><div class="sub_top fl">单价</div><div class="sub_top fl">数量</div><div class="sub_top fl">小计</div><div class="sub_top fr">操作</div><div class="clear"></div></div><th:block th:each="item : ${myShoppingCartItems}"><div class="content2 center"><div class="sub_content fl "></div><div class="sub_content cover fl"><img th:src="@{${item.goodsCoverImg}}"></div><div class="sub_content fl ft20" th:text="${item.goodsName}">商品名称</div><div class="sub_content fl" th:text="${item.sellingPrice+'元'}">1299元</div><div class="sub_content fl"><input class="goods_count" th:id="${'goodsCount'+item.cartItemId}" type="number"th:onblur="'updateItem('+${item.cartItemId}+')'"th:value="${item.goodsCount}" step="1" min="1"max="5"></div><div class="sub_content fl" th:text="${item.goodsCount*item.sellingPrice+'元'}">1299元</div><div class="sub_content fl"><a href="##" th:onclick="'deleteItem('+${item.cartItemId}+')'">×</a></div><div class="clear"></div></div></th:block></div></th:block><div class="pre_order mt20 center"><div class="tips fl ml20"><ul><li><a th:href="@{/index}">继续购物</a></li><li>|</li><li>共<span th:text="${itemsTotal}">13</span>件商品</li><div class="clear"></div></ul></div><div class="order_div fr"><div class="order_total fl">合计(不含运费):<span th:text="${priceTotal}+'.00元'">1299.00元</span></div><div class="order_button fr"><th:block th:if="${itemsTotal == 0}"><input class="order_button_c" type="button" name="tip"onclick="tip()"value="去结算"/></th:block><th:block th:unless="${itemsTotal == 0}"><input class="order_button_d" type="button" name="settle"onclick="settle()"value="去结算"/></th:block></div><div class="clear"></div></div><div class="clear"></div></div></div>
</div>
<div th:replace="mall/footer::footer-fragment"></div></body>
<!-- jQuery -->
<script th:src="@{/admin/plugins/jquery/jquery.min.js}"></script>
<script th:src="@{/admin/plugins/sweetalert2/sweetalert2.all.min.js}"></script>
<script type="text/javascript">/*** 购物车中数量为0时提示*/function tip() {Swal.fire({text: "购物车中无数据,无法结算",icon: "error",iconColor:"#f05b72",});}/*** 跳转至结算页面*/function settle() {window.location.href = '/shop-cart/settle'}/***更新购物项*/function updateItem(id) {var domId = 'goodsCount' + id;var goodsCount = $("#" + domId).val();if (goodsCount > 5) {Swal.fire({text: "单个商品最多可购买5个",icon: "error",iconColor:"#f05b72",});return;}if (goodsCount < 1) {Swal.fire({text: "数量异常",icon: "error",iconColor:"#f05b72",});return;}var data = {"cartItemId": id,"goodsCount": goodsCount};$.ajax({type: 'PUT',url: '/shop-cart',contentType: 'application/json',data: JSON.stringify(data),success: function (result) {if (result.resultCode == 200) {window.location.reload();} else {Swal.fire({text: "操作失败",icon: "error",iconColor:"#f05b72",});}},error: function () {Swal.fire({text: "操作失败",icon: "error",iconColor:"#f05b72",});}});}/*** * 删除购物项* @param id*/function deleteItem(id) {Swal.fire({title: "确认弹框",text: "确认要删除数据吗?",icon: "warning",iconColor:"#dea32c",showCancelButton: true,confirmButtonText: '确认',cancelButtonText: '取消'}).then((flag) => {if (flag.value) {$.ajax({type: 'DELETE',url: '/shop-cart/' + id,success: function (result) {if (result.resultCode == 200) {window.location.reload();} else {Swal.fire({text: "操作失败",icon: "error",iconColor:"#f05b72",});}},error: function () {Swal.fire({text: "操作失败",icon: "error",iconColor:"#f05b72",});}});}});}
</script>
</html>

        在购物项列表区域对应的位置读取myShoppingCartItems数据,首先使用th:each循环语法将商品标题字段、商品预览图字段、商品价格字段、商品数量字段、单个商品的总价字段进行渲染,然后读取读取底部两个小计字段并渲染至页面中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1540460.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

美元降息,对普通人有哪些影响?

美元降息&#xff0c;对普通人有哪些影响&#xff1f; 美元降息了。很多朋友都说我又不炒股&#xff0c;我手里又没有美金&#xff0c;美元跟我有啥关系啊&#xff1f;那我们就来聊聊美元降息&#xff0c;对我们国内经济到底有哪些影响&#xff1f;你再来看看跟你有没有关系&a…

短视频矩阵系统开发|技术源代码部署

产品功能亮点&#xff1a; 1. 支持多账号多平台一键 授权管理 2.支持矩阵视频批量剪辑&#xff0c;批量发布 3. 多平台关键词布局&#xff0c;提升企业及产品曝光 4. 评论区关键词自动回复&#xff0c;意向线索智能挖掘 5. 多账号投放数据统计&#xff0c;省时省力 6. 留资…

Jmeter 线程组解析

1.seUp线程组 一种特殊的 threadGroup &#xff0c;可用于执行预测试操作&#xff1b;它的行为完全像一个正常的线程组元件&#xff0c;不同的是执行顺序。 它会在普通线程组执行之前被触发。 应用场景&#xff1a; 测试数据库操作功能时&#xff0c;用于执行打开数据库连接的…

jetcache-阿里多级缓存框架神器一定要掌握

文章目录 1. 简介2. springboot集成jetcache2.1 引入依赖2.2 配置文件2.3 高级API模式&#xff1a;通过CacheManager使用缓存&#xff0c;2.7 版本才可使用2.4 &#xff08;推荐&#xff09;AOP模式&#xff1a;通过Cached,CacheUpdate,CacheInvalidate注解 1. 简介 JetCache是…

Redis基本命令详解

1. 基本命令 命令不区分大小写&#xff0c;而key是区分大小写的 # select 数据库间的切换 数据库共计16个 127.0.0.1:6379> select 1# dbsize 返回当前数据库的 key 的数量 127.0.0.1:6379[1]> dbsize# keys * 查看数据库所有的key 127.0.0.1:6379[1]> keys *# fl…

SpringBoot+Vue+MySQL驾校预约管理系统

目录 前言 功能设计 系统实现 获取源码 博主主页&#xff1a;百成Java 往期系列&#xff1a;Spring Boot、SSM、JavaWeb、python、小程序 前言 随着社会的进步&#xff0c;各行各业都在充分利用信息化时代的优势。由于计算机技术的广泛应用和普及&#xff0c;各种信息系统…

极越联手百度这你受得了吗!SU7还能稳坐“7字辈”头把交椅?

文/王俣祺 导语&#xff1a;自从今年上半年小米SU7标榜为“年轻人的第一台纯电轿车”&#xff0c;各家车企全都坐不住了。尤其是与小米“颇有渊源”的吉利&#xff0c;从极氪再到领克&#xff0c;目标已经可以说是路人皆知了。现在极越07也来了&#xff0c;可以看出吉利也是下了…

在Windows环境下设置SSH克隆GitHub仓库

在Windows环境下设置SSH克隆GitHub仓库的步骤如下&#xff1a; 1. 生成SSH密钥 打开 Git Bash&#xff08;如果你已经安装了Git&#xff09;。输入以下命令生成SSH密钥&#xff1a;ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" 按 Enter 键接受默认文件名…

OpenHarmony(鸿蒙南向开发)——小型系统内核(LiteOS-A)【内核通信机制】下

往期知识点记录&#xff1a; 鸿蒙&#xff08;HarmonyOS&#xff09;应用层开发&#xff08;北向&#xff09;知识点汇总 鸿蒙&#xff08;OpenHarmony&#xff09;南向开发保姆级知识点汇总~ 子系统开发内核 轻量系统内核&#xff08;LiteOS-M&#xff09; 轻量系统内核&#…

d3dcompiler47dll丢失怎么解决,详细介绍6种解决方案

在电脑使用过程中&#xff0c;我们可能会遇到各种问题&#xff0c;其中之一就是系统提示某个文件缺失。其中&#xff0c;d3dcompiler_47.dll是许多用户经常遇到的问题之一。这个文件是DirectX组件的一部分&#xff0c;如果缺失&#xff0c;可能会导致游戏或应用程序无法正常运行…

Python学习——【3.1】函数

文章目录 【3.1】函数一、函数的定义二、函数的参数三、函数的返回值&#xff08;一&#xff09;函数返回值的定义&#xff08;二&#xff09;None类型 四、函数的说明文档五、函数的嵌套调用六、函数中变量的作用域&#xff08;一&#xff09;局部变量&#xff08;二&#xff…

软考「系统架构设计师」为什么很少报名?反倒是“系规”爆火?!

软考2024年下半年开考的科目有不少&#xff0c;其中有热门科目&#xff0c;也有冷门科目&#xff0c;比如系统架构设计师&#xff0c;感觉报名的人数不多。 此外&#xff0c;系统规划与管理师算是在今年下半年爆火了……那么&#xff0c;系统架构设计师为什么很少报名&#xff…

前端自动化测试框架:如何选择最适合你的方案

前端自动化测试是指使用代码或工具来模拟用户在浏览器上的操作&#xff0c;以检验网页或应用程序的功能和性能是否符合预期。前端自动化测试可以提高开发效率&#xff0c;减少人工错误&#xff0c;保证软件质量和用户体验。 但是&#xff0c;在众多的前端自动化测试框架中&…

09.20 C++对C的扩充以及C++中的封装、SeqList

SeqList.h #ifndef SEQLIST_H #define SEQLIST_H#include <iostream> #include<memory.h> #include<stdlib.h> #include<string.h>using namespace std;//typedef int datatype; //类型重命名 using datatype int;//封装一个顺序表 class Seq…

【实用教程】基于GIS和DEM的地形地貌特征提取与分析—以河北省为例(附详细步骤)

实验背景 河北省作为中国地形地貌最齐全的省份&#xff0c;其独特的地理位置和地质结构为基于GIS和DEM的地形地貌特征提取与分析提供了丰富的研究对象和实际应用场景。从西北向东南呈半环状逐级下降&#xff0c;包括高原、山地、丘陵、盆地、平原等类型&#xff0c;这种多样性…

【HTML5】html5开篇基础(1)

1.❤️❤️前言~&#x1f973;&#x1f389;&#x1f389;&#x1f389; Hello, Hello~ 亲爱的朋友们&#x1f44b;&#x1f44b;&#xff0c;这里是E绵绵呀✍️✍️。 如果你喜欢这篇文章&#xff0c;请别吝啬你的点赞❤️❤️和收藏&#x1f4d6;&#x1f4d6;。如果你对我的…

python机器人编程——用手机web远程视频监控并控制小车驾驶(上篇vrep仿真)

目录 一、前言二、技术架构三、设备端实现四、服务控制端实现&#xff08;1&#xff09;摄像头服务模块&#xff08;2&#xff09;web服务器 五、web端实现&#xff08;1&#xff09;视频显示&#xff08;2&#xff09;驾驶盘的实现&#xff08;3&#xff09;心跳 六、总结七、…

情感类智能体——你的微信女神

智能体名称&#xff1a;你的微信女神 链接&#xff1a;文心智能体平台AgentBuilder | 想象即现实 (baidu.com)https://agents.baidu.com/agent/preview/RulbsUjIGj4wsinydlBH7AR3NQKFungt 简介 “你的微信女神”是一个直率的智能体&#xff0c;她用犀利而真实的言辞帮助用户…

Jboss CVE-2015-7501 靶场攻略

漏洞介绍 这是经典的JBoss反序列化漏洞&#xff0c;JBoss在/invoker/JMXInvokerServlet请求中读取了⽤户传⼊的对象&#xff0c;然后我们利⽤Apache Commons Collections中的 Gadget 执⾏任意代码 影响范围 JBoss Enterprise Application Platform 6.4.4,5.2.0,4.3.0_CP10 …

交易量大幅下滑,被华尔街投行下调目标价,是时候卖出Coinbase股票了吗?

猛兽财经核心观点&#xff1a; &#xff08;1&#xff09;由于交易量出现了大幅下滑&#xff0c;华尔街投行杰富瑞已经将Coinbase的目标下调到了220美元&#xff0c; &#xff08;2&#xff09;尽管2024年第二季度订阅和服务业务增长强劲&#xff0c;但Coinbase的财务业绩还是未…