19、【购物车模块】——加入购物车功能开发 ﹏ヽ暗。殇╰゛Y 2022-05-08 14:06 253阅读 0赞 购物车功能的开发是用户在前端将商品加入到购物车中的操作,加入的时候分两种情况,一种是商品已经在购物车里面了,如果用户再添加,我们只要增加对应的数量即可;第二种是原来购物车不存在该商品,我们要将该商品添加到购物车中。 \#\#\#\#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][image.png 1] [image.png]: /images/20220508/308b7613bd9049bf92d1e564595da946.png [image.png 1]: /images/20220508/4130aa684b704a25a3ff8c371b91d819.png
还没有评论,来说两句吧...