20、【购物车模块】——更新、删除、查询购物车功能开发

简介: 更新购物车,即修改购物车中的每个商品的参数,1、接口编写:1、更新购物车:*Controller:// 更新商品到购物车 @RequestMapping("update.

更新购物车,即修改购物车中的每个商品的参数,

1、接口编写:

1、更新购物车:

*Controller:

//    更新商品到购物车
    @RequestMapping("update.do")
    @ResponseBody
    public ServerResponse<CartVo> update(HttpSession session, Integer count, Integer productId){
        User user =(User) session.getAttribute(Const.CURRENT_USER);

        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iCartService.update(user.getId(),productId,count);
    }

*Service:

    //更新商品到购物车
    ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count);

*ServiceImpl:

 //    更新商品到购物车
    public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count) {

        if (productId == null || count == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCatByUserIdProductId(userId, productId);
        if (cart != null) {
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

selectCatByUserIdProductId方法:

*Mapper:


    //根据用户Id和产品Id去查购物车
    Cart selectCatByUserIdProductId(@Param("userId") Integer userId, @Param("productId") Integer productId);

*Mappler.xml:


  <!--根据用户Id和产品Id来查询购物车-->
  <select id="selectCatByUserIdProductId" resultMap="BaseResultMap" parameterType="map">
    select
    <include refid="Base_Column_List"/>
    from mmall_cart
    where user_id=#{userId}
    and product_id=#{productId}
  </select>
2、删除商品:

*Controller:

    //    移除购物车某个产品
    @RequestMapping("delete_product.do")
    @ResponseBody
    public ServerResponse<CartVo> deleteProduct(HttpSession session, String productIds){
        User user =(User) session.getAttribute(Const.CURRENT_USER);

        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
      return iCartService.deleteProduct(user.getId(),productIds);
    }

*Service:

    //删除购物车中的商品
    ServerResponse<CartVo> deleteProduct(Integer userId,String productIds);

*ServiceImpl:


    //删除购物车中的商品
    public ServerResponse<CartVo> deleteProduct(Integer userId, String productIds) {
        List<String> productList = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productList)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdProductIds(userId, productList);
        return this.list(userId);
    }

deleteByUserIdProductIds方法:
*Mapper:

    //删除购物车中的商品
    int deleteByUserIdProductIds(@Param("userId") Integer userId,@Param("productIdList")List<String> productIdList);

*Mappler.xml:

  <delete id="deleteByUserIdProductIds" parameterType="map">
    delete from mmall_cart
    where user_id = #{userId}
    <if test="productIdList != null">
      and product_id in
        <foreach collection="productIdList" item="item" index="index" open="(" separator="," close=")">
          #{item}
        </foreach>
    </if>
  </delete>
其中上面的list是我们封装的一个返回购物车列表信息的接口,,

*Controller:

    //查询购物车中商品
    @RequestMapping("list.do")
    @ResponseBody
    public ServerResponse<CartVo> list(HttpSession session){
        User user =(User) session.getAttribute(Const.CURRENT_USER);

        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
       return iCartService.list(user.getId());
    }

*Service:

    //查询购物车中商品
    ServerResponse<CartVo> list(Integer userId);

*ServiceImpl:

    //查询购物车中商品
    public ServerResponse<CartVo> list(Integer userId) {
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

重点看一下getCartVoLimit这个方法:


    //封装的一个根据用户Id来获取购物车信息的方法
    private CartVo getCartVoLimit(Integer userId) {
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);

        List<CartProductVo> cartProductVoList = Lists.newArrayList();

        //设置购物车初始总价
        BigDecimal cartTotalPrice = new BigDecimal("0.0");

        if (CollectionUtils.isNotEmpty(cartList)) {
            for (Cart cartItem : cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());

                Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());

                if (product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductPrice(product.getPrice());

                    cartProductVo.setProductStock(product.getStock());

                    //判断库存

                    int buyLimitCount =0;

                        if (product.getStock()>=cartItem.getQuantity()) {
                            //库存充足的时候
                            buyLimitCount = cartItem.getQuantity();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_MUM_SUCCESS);
                        } else {
                            //库存的不足的时候
                            buyLimitCount = product.getStock();
                            cartProductVo.setLimitQuantity(Const.Cart.LIMIT_MUM_FAIL);
                            //购物车中更新有效库存

                            Cart cartForQuantity = new Cart();
                            cartForQuantity.setId(cartItem.getId());
                            cartForQuantity.setQuantity(buyLimitCount);
                            cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                        }

                    cartProductVo.setQuantity(buyLimitCount);

                    //计算总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                    cartProductVo.setProductChecked(cartItem.getChecked());
                }

                if (cartItem.getChecked() == Const.Cart.CHECKED) {
                    //如果已经勾选,增加到整个购物车总价中

                    if(cartProductVo.getProductTotalPrice() == null){
                    }

                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());

                }
                cartProductVoList.add(cartProductVo);
            }
        }

        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return cartVo;
    }

上面封装的getAllCheckedStatus方法:

    //封装的购物车中商品的是否选中状态
    private boolean getAllCheckedStatus(Integer userId) {
        if (userId == null) {
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }

selectCartProductCheckedStatusByUserId:
cartMapper:

    //根据用户Id查询商品是否被选中
    int selectCartProductCheckedStatusByUserId(Integer userId);

cartMapper.xml:

  <select id="selectCartProductCheckedStatusByUserId" resultType="int" parameterType="int" >
    select count(1) from mmall_cart where checked = 0 and user_id = #{userId}
  </select>

上面方法中使用的CartVo:

package com.mmall.vo;

import java.math.BigDecimal;
import java.util.List;

public class CartVo {

    private List<CartProductVo> cartProductVoList;

    private BigDecimal cartTotalPrice;
    private Boolean allChecked; //是否都勾选
    private String imageHost;

    public List<CartProductVo> getCartProductVoList() {
        return cartProductVoList;
    }

    public void setCartProductVoList(List<CartProductVo> cartProductVoList) {
        this.cartProductVoList = cartProductVoList;
    }

    public BigDecimal getCartTotalPrice() {
        return cartTotalPrice;
    }

    public void setCartTotalPrice(BigDecimal cartTotalPrice) {
        this.cartTotalPrice = cartTotalPrice;
    }

    public Boolean getAllChecked() {
        return allChecked;
    }

    public void setAllChecked(Boolean allChecked) {
        this.allChecked = allChecked;
    }

    public String getImageHost() {
        return imageHost;
    }

    public void setImageHost(String imageHost) {
        this.imageHost = imageHost;
    }
}

ProductVo:

package com.mmall.vo;

import java.math.BigDecimal;

public class CartProductVo {

    //结合了产品和购物车的一个抽象对象

    private Integer Id;
    private Integer userId;
    private Integer productId;
    private Integer quantity;//购物车中该商品的数量
    private String productName;
    private String productSubtitle;
    private String productMainImage;
    private BigDecimal productPrice;
    private Integer productStatus;
    private BigDecimal productTotalPrice;
    private Integer productStock;
    private Integer productChecked; //该产品是否勾选

    private String limitQuantity; //限制数量的一个返回结果

    public Integer getId() {
        return Id;
    }

    public void setId(Integer id) {
        Id = id;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductSubtitle() {
        return productSubtitle;
    }

    public void setProductSubtitle(String productSubtitle) {
        this.productSubtitle = productSubtitle;
    }

    public String getProductMainImage() {
        return productMainImage;
    }

    public void setProductMainImage(String productMainImage) {
        this.productMainImage = productMainImage;
    }

    public BigDecimal getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(BigDecimal productPrice) {
        this.productPrice = productPrice;
    }

    public Integer getProductStatus() {
        return productStatus;
    }

    public void setProductStatus(Integer productStatus) {
        this.productStatus = productStatus;
    }

    public BigDecimal getProductTotalPrice() {
        return productTotalPrice;
    }

    public void setProductTotalPrice(BigDecimal productTotalPrice) {
        this.productTotalPrice = productTotalPrice;
    }

    public Integer getProductStock() {
        return productStock;
    }

    public void setProductStock(Integer productStock) {
        this.productStock = productStock;
    }

    public Integer getProductChecked() {
        return productChecked;
    }

    public void setProductChecked(Integer productChecked) {
        this.productChecked = productChecked;
    }

    public String getLimitQuantity() {
        return limitQuantity;
    }

    public void setLimitQuantity(String limitQuantity) {
        this.limitQuantity = limitQuantity;
    }
}

2、接口测试:

1、用户购物车信息接口测试:
img_748da03b92e188ec6ad018aae61dda33.png
image.png
2、更新商品数量到购物车接口测试:
img_cdeac4af9dc483c763b704dd533aecc2.png
image.png
3、移除购物车某个产品接口测试:我们可以传入商品信息id单个或多个进行删除~
img_96210f38bef585026aea4f1aa7e688f7.png
image.png
相关文章
|
JSON API 数据格式
微店商品列表API接口文档
微店商品列表API(micro.item_search)支持通过关键词、分页和筛选条件获取商品信息,返回含ID、名称、价格、库存、图片等JSON数据。适用于电商工具、竞品分析等场景,具备分页灵活、数据实时等优势。
|
机器学习/深度学习 数据安全/隐私保护 UED
淘宝图片搜索接口开发指南:从图像识别到商品匹配的全流程实现
图片搜索技术极大提升了电商用户体验。本文详解淘宝图片搜索接口的实现原理与开发实战,涵盖预处理、特征提取、比对与结果返回等核心流程,并提供可复用代码。内容还包括常见错误处理、合规性开发注意事项及多种扩展应用场景,助力开发者快速构建高效、合规的图片搜索功能。
淘宝图片搜索接口开发指南:从图像识别到商品匹配的全流程实现
|
Ubuntu 安全 Linux
Ubuntu 24.10 发行版登场:Linux 6.11 内核、GNOME 47 桌面环境
Ubuntu 24.10 还带来了 GNOME 47,增强了性能和稳定性,并引入了新功能。此版本的 Ubuntu 还默认在采用 Nvidia 显卡的硬件上切换到 Wayland,并在支持的硬件上默认使用开源的 Nvidia 560 内核模块。 另外需要注意的是,Ubuntu 24.10 是稳定版本,但作为非 LTS 版本,仅支持 9 个月。
|
图形学
Unity UGUI拖拽移动
本文介绍了两种UI拖拽实现方式:精准拖拽和克隆拖拽。精准拖拽通过计算鼠标点击点与UI中心的偏移量,使UI跟随鼠标移动,适用于需要精确控制的场景。代码中通过`IBeginDragHandler`、`IDragHandler`和`IEndDragHandler`接口实现拖拽逻辑。克隆拖拽则在拖拽时克隆一个UI对象,使其跟随鼠标移动,适合视觉效果需求较高的场景。代码中同样使用上述接口,并在拖拽结束时销毁克隆对象。具体实现可参考提供的代码示例。
897 10
|
传感器 人工智能 搜索推荐
只靠一个头,能做出被“可爱攻击”的AI智能宠物吗?
本文探讨了AI实体化的一个具体方向——AI智能宠物,尤其是仅靠“一个头”设计的可行性与潜力。相比复杂的人形机器人,头部AI宠物成本更低、技术门槛更小,且能聚焦语言和表情交互,打造情感连接。文章分析了AI宠物的市场机遇,如满足孤独经济需求、成为消费电子新趋势,并指出“可爱”只是入场券,真正留住用户的在于深度交互体验。最后强调,精准洞察用户需求是关键,避免陷入“有趣但无用”的陷阱,为AI实体化找到切实可行的商业化路径。
651 0
|
存储 NoSQL 关系型数据库
【赵渝强老师】MongoDB的存储结构
MongoDB 是一个可移植的 NoSQL 数据库,支持跨平台运行。其逻辑存储结构包括数据库、集合和文档,而物理存储结构则由命名空间文件、数据文件和日志文件组成。视频讲解和示意图进一步解释了这些概念。
772 5
|
开发者 Python
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
1540 0
|
存储 算法 Linux
在Linux中,有哪些备份和恢复工具?
在Linux中,有哪些备份和恢复工具?
|
人工智能 决策智能
【AI Agent系列】【阿里AgentScope框架】3. 深入源码:Pipeline模块如何组织多智能体间的数据流?- 顺序结构与条件分支
【AI Agent系列】【阿里AgentScope框架】3. 深入源码:Pipeline模块如何组织多智能体间的数据流?- 顺序结构与条件分支
846 2
|
C# 开发者 Windows
4款.NET开源、功能强大的Windows桌面工具箱
4款.NET开源、功能强大的Windows桌面工具箱
724 0