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

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

1、接口编写:

新建CartController类:

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、添加商品到购物车接口测试
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 Mybatis入门 1.1 单独使用jdbc编程问题总结 1.1.1 jdbc程序 上边使...
    哇哈哈E阅读 3,343评论 0 38
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,860评论 25 709
  • 大抵是无味的爱情 如果你在思考他爱不爱你 大抵是不爱 如果每一天都想要去分手 大抵不爱 如果被利益牵扯 大抵不爱 ...
    一块瘦司阅读 215评论 1 1
  • 她出生在长崎一个富裕的家庭。她喜欢美好的事物。她最喜欢插花。 她不喜欢那些政客的鼓动,也不喜欢那些...
    珝渊阅读 294评论 0 0
  • 声音从空中飘落 掉在哪里了 我埋头找了许久 也找不到 从小鸟嘴里滑走的 叽叽喳喳
    望小童阅读 301评论 0 3