19、【购物车模块】——加入购物车功能开发

购物车功能的开发是用户在前端将商品加入到购物车中的操作,加入的时候分两种情况,一种是商品已经在购物车里面了,如果用户再添加,我们只要增加对应的数量即可;第二种是原来购物车不存在该商品,我们要将该商品添加到购物车中。

1、接口编写:

新建CartController类:

img_a3bc448fab2c3b90fed8f6dcc6c31e64.png
image.png

*Controller:

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

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

*Service:

    //添加商品到购物车
    ServerResponse<CartVo> add(Integer userId, Integer productId, Integer count);

*ServiceImpl:

 //添加商品到购物车
    public ServerResponse<CartVo> add(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 cartItem = new Cart();
            cartItem.setQuantity(count);
            cartItem.setChecked(Const.Cart.CHECKED);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            cartMapper.insert(cartItem);
        } else {
            //产品已经在购物车
            //如果产品已存在购物车,则数量相加
            count = cart.getQuantity() + count;
            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、接口测试:
1、添加商品到购物车接口测试
img_263996e8fcfe90bc724b919ddb09c5b7.png
image.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值