新峰商城之购物车(三)

        在购物车列表中可以编辑需要购买的商品数量,也可以将商品从购物车中删除,本文将简述以上两个功能的实现过程和代码。

一、数据层

在Mapper接口的NewBeeMallShoppingCartItemMapprer.java增加方法如下:

//根据主键查询记录
NewBeeMallShoppingCartItem selectByPrimaryKey(Long cartItemId);
//修改记录
int updateByPrimaryKeySelective(NewBeeMallShoppingCartItem record);
//删除记录
int deleteByPrimaryKey(Long cartItemId);

在映射文件NewBeeMallShoppingCartItemMapprer.xml中增加代码如下:

<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_newbee_mall_shopping_cart_item
        where cart_item_id = #{cartItemId,jdbcType=BIGINT} and is_deleted = 0
</select>

<update id="updateByPrimaryKeySelective" parameterType="ltd.newbee.mall.entity.NewBeeMallShoppingCartItem">
        update tb_newbee_mall_shopping_cart_item
        <set>
            <if test="userId != null">
                user_id = #{userId,jdbcType=BIGINT},
            </if>
            <if test="goodsId != null">
                goods_id = #{goodsId,jdbcType=BIGINT},
            </if>
            <if test="goodsCount != null">
                goods_count = #{goodsCount,jdbcType=INTEGER},
            </if>
            <if test="isDeleted != null">
                is_deleted = #{isDeleted,jdbcType=TINYINT},
            </if>
            <if test="createTime != null">
                create_time = #{createTime,jdbcType=TIMESTAMP},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime,jdbcType=TIMESTAMP},
            </if>
        </set>
        where cart_item_id = #{cartItemId,jdbcType=BIGINT}
</update>

<update id="deleteByPrimaryKey" parameterType="java.lang.Long">
    update tb_newbee_mall_shopping_cart_item set is_deleted = 1
    where cart_item_id = #{cartItemId,jdbcType=BIGINT} and is_deleted = 0
</update>

二、业务层

在业务类NewBeeMallShoppingCartService中增加如下方法:

 /**
     * 修改购物车中的属性
     *
     * @param newBeeMallShoppingCartItem
     * @return
     */
String updateNewBeeMallCartItem(NewBeeMallShoppingCartItem newBeeMallShoppingCartItem);
  /**
     * 删除购物车中的商品
     *
     *
     * @param shoppingCartItemId
     * @param userId
     * @return
     */
Boolean deleteById(Long shoppingCartItemId, Long userId);

在业务实现类NewBeeMallShoppingCartServiceImpl中增加如下方法:

@Override
public String updateNewBeeMallCartItem(NewBeeMallShoppingCartItem newBeeMallShoppingCartItem) {
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItemUpdate = newBeeMallShoppingCartItemMapper.selectByPrimaryKey(newBeeMallShoppingCartItem.getCartItemId());
        if (newBeeMallShoppingCartItemUpdate == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        //超出单个商品的最大数量
        if (newBeeMallShoppingCartItem.getGoodsCount() > Constants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            return ServiceResultEnum.SHOPPING_CART_ITEM_LIMIT_NUMBER_ERROR.getResult();
        }
        //当前登录账号的userId与待修改的cartItem中userId不同,返回错误
        if (!newBeeMallShoppingCartItemUpdate.getUserId().equals(newBeeMallShoppingCartItem.getUserId())) {
            return ServiceResultEnum.NO_PERMISSION_ERROR.getResult();
        }
        //数值相同,则不执行数据操作
        if (newBeeMallShoppingCartItem.getGoodsCount().equals(newBeeMallShoppingCartItemUpdate.getGoodsCount())) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        newBeeMallShoppingCartItemUpdate.setGoodsCount(newBeeMallShoppingCartItem.getGoodsCount());
        newBeeMallShoppingCartItemUpdate.setUpdateTime(new Date());
        //修改记录
        if (newBeeMallShoppingCartItemMapper.updateByPrimaryKeySelective(newBeeMallShoppingCartItemUpdate) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }


@Override
public Boolean deleteById(Long shoppingCartItemId, Long userId) {
        NewBeeMallShoppingCartItem newBeeMallShoppingCartItem = newBeeMallShoppingCartItemMapper.selectByPrimaryKey(shoppingCartItemId);
        if (newBeeMallShoppingCartItem == null) {
            return false;
        }
        //userId不同不能删除
        if (!userId.equals(newBeeMallShoppingCartItem.getUserId())) {
            return false;
        }
        return newBeeMallShoppingCartItemMapper.deleteByPrimaryKey(shoppingCartItemId) > 0;
    }

updateNewMallCartItem()方法,首先对参数进行校验,校验步骤如下所示:

(1)首先根据前端传参的购物项主键id查询购物项表中是否存在记录,若不存在则返回错误信息,若存在则继续操作。

(2)判断用户购物车中的商品数量是否已超出最大限制

在校验通过后再进行修改操作,将此购物项的数量和时间进行修改。

        deleteById()方法将此购物项的is_deleted字段修改为1,并非物理删除,而是逻辑删除。

三、控制层

在ShoppingCartController中增加修改购物项和删除购物项两个方法,代码如下所示:

//修改购物项
    @PutMapping("/shop-cart")
    @ResponseBody
    public Result updateNewBeeMallShoppingCartItem(@RequestBody NewBeeMallShoppingCartItem newBeeMallShoppingCartItem,
                                                   HttpSession httpSession) {
        NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        newBeeMallShoppingCartItem.setUserId(user.getUserId());
        String updateResult = newBeeMallShoppingCartService.updateNewBeeMallCartItem(newBeeMallShoppingCartItem);
        //修改成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(updateResult)) {
            return ResultGenerator.genSuccessResult();
        }
        //修改失败
        return ResultGenerator.genFailResult(updateResult);
    }

//删除购物项
    @DeleteMapping("/shop-cart/{newBeeMallShoppingCartItemId}")
    @ResponseBody
    public Result updateNewBeeMallShoppingCartItem(@PathVariable("newBeeMallShoppingCartItemId") Long newBeeMallShoppingCartItemId,
                                                   HttpSession httpSession) {
        NewBeeMallUserVO user = (NewBeeMallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        Boolean deleteResult = newBeeMallShoppingCartService.deleteById(newBeeMallShoppingCartItemId,user.getUserId());
        //删除成功
        if (deleteResult) {
            return ResultGenerator.genSuccessResult();
        }
        //删除失败
        return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
    }

        在此Controller类中有几个方法的路径都是/shop-cart,不同的请求方法就是接口的区分方式,POST方法是新增接口,GET方法是购物车列表项页面显示,PUT方法是修改接口,DELETE是购物项删除接口。

        编辑功能主要是修改购物项的数量,后端编辑接口负责接收前端传入的cartItemId和goodsCount参数,根据这两个参数修改购物项的数量值。

        删除功能主要是进行购物项的逻辑删除,后端删除接口负责接收cartItemId 参数,根据此参数修改购物项的is_deleted的值为1。

四、前端

修改数量按钮的实现逻辑通过列表中商品数量 input框的onblur()事件类实现,首先给商品数量输入框绑定onblur事件,代码如下:

<input class="goods_count" th:id="${'goodsCount'+item.cartItemId}"
    type="number"  th:onblur="'updateItem('+${item.cartItemId}+')'"
    th:value="${item.goodsCount}" step="1"  max="5">

当用户鼠标焦点离开input输入框时就会触发updateItem()方法,此方法会向后端发送修改购物数量的请求,在cart.html模板文件中新增代码如下所示:

 /**
     *更新购物项
     */
    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",
                });
            }
        });
    }

  

此方法具体执行步骤如下所示:

(1)获取购物项主键id和修改后的数量

(2)进行基本的正则验证,修改数量不能大于5且不小于1

(3)向后端购物项修改接口发送请求

 (4)根据接口回调进行后续操作

每个购物项的显示区都有一个删除按钮,删除按钮也绑定触发事件,绑定的方法是delteItem(),在cart.html模板文件中的购物项列表区域增加代码如下所示:

<div class="sub_content fl"><a href="##" th:onclick="'deleteItem('+${item.cartItemId}+')'">×</a>

deleteItem()方法的代码如下所示:

  /**
     * * 删除购物项
     * @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",
                            });
                        }
                    });
                }
            });
}

        此方法在让用户确认后,获取需要删除的购物项id并向后端发送删除请求,后端执行逻辑删除操作,传送操作信息至前端,失败则返回错误信息,成功则刷新页面,完成删除操作。

### 新蜂商城的使用指南与开发文档 #### 1. 构建工具配置 构建系统的配置文件 `build.gradle` 或者 `pom.xml` 是项目的核心部分之一,用于定义项目的依赖项以及编译、打包和发布的具体指令。这些文件的存在使得开发者可以轻松管理复杂的依赖关系并自动化许多重复性的任务[^1]。 对于采用 Gradle 的项目而言,在 `build.gradle` 文件中会指定插件版本号、库依赖列表以及其他必要的设置参数;而 Maven 用户则通过编辑其对应的 XML 配置来实现相同目的——即确保所有必需组件都被正确引入到工程当中以便顺利完成整个软件生命周期内的各项操作流程。 #### 2. 应用程序属性配置 在 Spring Boot 框架下运行的新蜂商城还需要关注另一个重要方面:应用程序级别的个性化调整选项通常存储于名为 `application.properties` 或 YAML 格式的同名替代品之中。这类资源允许管理员自定义端口号、数据库连接字符串等敏感数据而不必修改源码本身即可生效[^1]。 #### 3. 客户端前端架构概述 针对基于现代 JavaScript 技术栈所打造出来的全新一代 web 应用场景解决方案—newbee-mall-vue3-app 提供了一个完整的实例演示如何利用 Vue.js 生态圈中的最新成果快速搭建起功能齐全且用户体验优秀的在线购物平台界面布局设计思路及其背后的技术细节描述如下: 该项目采用了当前流行的 Vue3 全家桶作为主要框架支持,并辅以 vue-router 路由管理和 pinia 状态管理模式共同协作完成跨组件间通信需求处理工作流的同时还集成了 vant UI 组件库从而极大简化了日常编码过程中频繁遇到的一些常见交互逻辑实现难度降低维护成本提升效率等方面均表现出色[^2]。 ```javascript // 示例代码片段展示Pinia状态管理器基本用法 import { defineStore } from 'pinia'; export const useCartStore = defineStore('cart', { state: () => ({ items: [] }), actions: { addItem(item){ this.items.push(item); } } }); ``` #### 4. Java 运行时环境准备 如果计划部署该服务至类 Unix 平台之上,则可能需要提前做好 JDK 安装及相关路径映射等工作步骤指导信息可参见下面给出的具体命令行脚本样例内容说明材料里提到过相关内容可供参考学习之用[^3]: ```bash vim /etc/profile # 添加以下几行 export JAVA_HOME=/usr/local/src/jdk1.8 export PATH=${JAVA_HOME}/bin:${PATH} export CLASSPATH=.:${JAVA_HOME}/lib/tools.jar source /etc/profile java -version ``` 以上就是关于新蜂商城从后端服务器端一直到客户端表现层各个层面涉及到的主要知识点总结归纳希望能够帮助您更好地理解和掌握这个开源电商系统整体运作原理!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值