购物车模块技术要点:
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