表现层
/**
* 更新购物车
*/
public E3Result updateCartNum(long userId, long itemId, int num) {
//根据用户id查询用户列表
String json = jedisClient.hget(REDIS_CART_PRE+":"+userId, itemId+"");
//更新商品数量
TbItem item = JsonUtils.jsonToPojo(json, TbItem.class);
item.setNum(num);
//写入Redis
jedisClient.hset(REDIS_CART_PRE+":"+userId, itemId+"",JsonUtils.objectToJson(item));
return E3Result.ok();
}
/**
* 删除购物车
*/
public E3Result deleteCartItem(long userId, long itemId) {
//根据用户id查询用户列表
jedisClient.hdel(REDIS_CART_PRE+":"+userId, itemId+"");
return E3Result.ok();
}
表现层的实现
/**
* 更新购物车商品的数量
*/
@RequestMapping("/cart/update/num/{itemId}/{num}")
@ResponseBody
public E3Result updateCatNum(@PathVariable Long itemId,@PathVariable Integer num,
HttpServletRequest request,HttpServletResponse response){
//判断用户是否登录
TbUser user = (TbUser) request.getAttribute("user");
if(user !=null){
cartService.updateCartNum(user.getId(), itemId, num);
return E3Result.ok();
}
//1.取出购物车的列表
List<TbItem> itemList = getCartListFromCookie(request);
//2.遍历列表,找到对应的商品
for(TbItem item :itemList){
if(item.getId().longValue() == itemId){
//3.更新数量
item.setNum(num);
break;
}
}
//4.把购物车列表写回Cookie
CookieUtils.setCookie(request, response,"cart",JsonUtils.objectToJson(itemList),COOKIE_CART_EXPIRE,true);
//5.返回成功
return E3Result.ok();
}
/**
* 删除购物车商品
*/
@RequestMapping("/cart/delete/{itemId}")
public String deleteCartItem(@PathVariable Long itemId, HttpServletRequest request,
HttpServletResponse response) {
//判断用户是否为登录状态
TbUser user = (TbUser) request.getAttribute("user");
//如果是登录状态,把购物车写入Redis
if (user != null) {
//保存到服务器
cartService.deleteCartItem(user.getId(), itemId);
//返回逻辑视图
return "redirect:/cart/cart.html";
}
//从cookie中取购物车列表
List<TbItem> cartList = getCartListFromCookie(request);
//遍历列表,找到要删除的商品
for (TbItem tbItem : cartList) {
if (tbItem.getId().longValue() == itemId) {
//删除商品
cartList.remove(tbItem);
//跳出循环
break;
}
}
//把购物车列表写入cookie
CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
//返回逻辑视图,跳转到下面的页面
return "redirect:/cart/cart.html";
}
观察结果
图片.png图片.png
网友评论