Java之品优购课程讲义_day16(2)

2.1 后端控制层
实现思路:
(1)从 cookie 中取出购物车
(2)向购物车添加商品
(3)将购物车存入 cookie
pinyougou-cart-web 工程新建 CartController.java

@RestController
@RequestMapping("/cart")

public  class  CartController  {

@Reference

private  CartService  cartService;

@Autowired

private    HttpServletRequest  request;

@Autowired

private    HttpServletResponse  response;

/**

*购物车列表

*@param  request

*@return

*/ @RequestMapping("/findCartList")
public  List  findCartList(){

String  cartListString  =  util.CookieUtil.getCookieValue(request, "cartList","UTF-8");

if(cartListString==null  ||  cartListString.equals("")){ cartListString="[]";

List  cartList_cookie  =  JSON.parseArray(cartListString,  Cart.class);

return  cartList_cookie;

}

/**

*添加商品到购物车

*@param  request

*@param  response

*@param  itemId

*@param  num

*@return

*/ @RequestMapping("/addGoodsToCartList")
public  Result  addGoodsToCartList(Long  itemId,Integer  num){

try {

List  cartList  =findCartList();//获取购物车列表
cartList  =  cartService.addGoodsToCartList(cartList,  itemId,  num); util.CookieUtil.setCookie(request,  response,  "cartList",
JSON.toJSONString(cartList),3600*24,"UTF-8");

return  new  Result(true,  "添加成功");

}  catch  (Exception  e)  { e.printStackTrace();
return  new  Result(false,  "添加失败");

}

}

浏览器测试:
查看购物车:http://localhost:9105/cart/findCartList.do 添加商品到购物车 :
http://localhost:9105/cart/addGoodsToCartList.do?itemId=1369280&num=100

你可能感兴趣的:(JAVA)