这里传入的参数是skuId(库存表的主键, 库存表保存的商品id,颜色,尺码,库存等信息), 购买数量amount.
接着我们来看Controller是如何来处理的:
1 //加入购物车
2 @RequestMapping(value=“/shopping/buyerCart”)
3 public String buyerCart(Long skuId, Integer amount, HttpServletRequest request,
4 HttpServletResponse response) throws JsonParseException, JsonMappingException, IOException{
5 //将对象转换成json字符串/json字符串转成对象
6 ObjectMapper om = new ObjectMapper();
7 om.setSerializationInclusion(Include.NON_NULL);
8 BuyerCart buyerCart = null;
9 //1,获取Cookie中的购物车
10 Cookie[] cookies = request.getCookies();
11 if (null != cookies && cookies.length > 0) {
12 for (Cookie cookie : cookies) {
13 //
14 if (Constants.BUYER_CART.equals(cookie.getName())) {
15 //购物车 对象 与json字符串互转
16 buyerCart = om.readValue(cookie.getValue(), BuyerCart.class);
17 break;
18 }
19 }
20 }
21
22 //2,Cookie中没有购物车, 创建购物车对象
23 if (null == buyerCart) {
24 buyerCart = new BuyerCart();
25 }
26
27 //3, 将当前款商品追加到购物车
28 if (null != skuId && null != amount) {
29 Sku sku = new Sku();
30 sku.setId(skuId);
31 BuyerItem buyerItem = new BuyerItem();
32 buyerItem.setSku(sku);
33 //设置数量
34 buyerItem.setAmount(amount);
35 //添加购物项到购物车
36 buyerCart.addItem(buyerItem);
37 }
38
39 //排序 倒序
40 List items = buyerCart.getItems();
41 Collections.sort(items, new Comparator() {
42
43 @Override
44 public int compare(BuyerItem o1, BuyerItem o2) {
45 return -1;
46 }
47
48 });
49
50 //前三点 登录和非登录做的是一样的操作, 在第四点需要判断
51 String username = sessionProviderService.getAttributterForUsername(RequestUtils.getCSessionId(request, response));
52 if (null != username) {
53 //登录了
54 //4, 将购物车追加到Redis中
55 cartService.insertBuyerCartToRedis(buyerCart, username);
56 //5, 清空Cookie 设置存活时间为0, 立马销毁
57 Cookie cookie = new Cookie(Constants.BUYER_CART, null);
58 cookie.setPath(“/”);
59 cookie.setMaxAge(-0);
60 response.addCookie(cookie);
61 }else {
62 //未登录
63 //4, 保存购物车到Cookie中
64 //将对象转换成json格式
65 Writer w = new StringWriter();
66 om.writeValue(w, buyerCart);
67 Cookie cookie = new Cookie(Constants.BUYER_CAR