Java电商项目面试--购物车模块

本文探讨了电商项目中的购物车模块,重点介绍了如何实现商品总价计算的复用封装、高复用逻辑方法封装,以及如何解决商业运算中浮点数精度丢失的问题。内容涵盖购物车功能如添加、更新商品数量、查询、移除商品以及单选/全选操作,并展示了相关Controller层、Service层及Mapper.xml的实现。
摘要由CSDN通过智能技术生成

购物车模块技术要点:
1、商品总价计算复用封装
2、高复用的逻辑方法封装思想
3、解决商业运算丢失精度的坑

一、购物车模块功能
1、购物车添加商品
2、更新商品数量
3、查询商品数量
4、移除购物车中商品
5、单选/全选
二、购物车添加商品
Controller层:

//购物车添加商品
@RequestMapping("add.do")
@ResponseBody
public ServerResponse<CartVo> add(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.add(user.getId(),productId,count);
}

Service层:

//购物车添加商品
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.selectCartByUserIdProductId(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);
}
//返回之前需要判断一下(这里将这个函数封装了一下)
public ServerResponse<CartVo> list (Integer userId){
    CartVo cartVo = this.getCartVoLimit(userId);
    return ServerResponse.createBySuccess(cartVo);
}
//限制购物车中商品数量
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(cart
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北极星小王子

你的鼓励是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值