一、大概思路
1、从cookie中取商品列表
2、判断要添加的商品是否存在cookie中。
3、如果已添加过,则把对应的商品取出来,把要添加的商品的数量加上去。
4、如果没有添加过,则把改商品添加到商品列表中。
5、再把商品列表序列化,加入cookie中。
二、代码实现
1、定义一个购物车商品的pojo
public class CartItem { private Long id; private String title; private Long price; private Integer num; private String image; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getPrice() { return price; } public void setPrice(Long price) { this.price = price; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
2、定义一个购物车的接口和实现类
public interface CartService { TaotaoResult addCartService(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num); }
@Service public class CartServiceImpl implements CartService { @Autowired private ItemService itemService; @Value("${COOKIE_EXPIRE}") private Integer COOKIE_EXPIRE; @Override public TaotaoResult addCartService(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) { // 1.从cookie中取商品列表 List<CartItem> list = getCartFromCookie(request); // 2.判断是否已经添加过购物车 boolean haveflag = false; for (CartItem c : list) { //3.如果添加过,把对应的商品取出来,数量加Num if(c.getId().longValue() == itemId) { c.setNum(c.getNum() + num); haveflag = true; break; } } // 4.如果没添加过,则把该商品添加进去。 if (!haveflag) { TbItem item = itemService.getItemById(itemId); CartItem cartItem = new CartItem(); cartItem.setNum(num); cartItem.setId(itemId); cartItem.setPrice(item.getPrice()); cartItem.setTitle(item.getTitle()); if (item.getImage() != null) { String image = item.getImage(); String[] strings = image.split(","); cartItem.setImage(strings[0]); } list.add(cartItem); } // 5.再把list返回到cookie中 CookieUtils.setCookie(request, response, "TT_CART", JsonUtils.objectToJson(list), COOKIE_EXPIRE);
return TaotaoResult.ok(); } private List<CartItem> getCartFromCookie(HttpServletRequest request) { try { String json = CookieUtils.getCookieValue(request, "TT_TOKEN", true); List<CartItem> list = JsonUtils.jsonToList(json, CartItem.class); if (list == null) { return new ArrayList<>(); }else { return list; } }catch (Exception e) { return new ArrayList<>(); } } }
3、controller来接收前端的请求,并响应到cart-success.jsp页面。
@Controller public class CartController { @Autowired private CartService cartService; @RequestMapping("/cart/add/{itemId}") public String addCart(@PathVariable Long itemId, Integer num, HttpServletRequest request, HttpServletResponse response) { TaotaoResult result = cartService.addCartService(request, response, itemId, num); return "cart-success"; } }