通过Cookie实现购物车
加一句闲话,我的个人博客雷园的个人博客,我的文章都会在个人博客同步更新
闲话就不说了直接上代码了
导包:
import com.ambow.springboot.vo.CartVo;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
获取Cookie
/**
* 获取名为"cart"的cookie
*
* @param request
* @return cookie
*/
public Cookie getCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
Cookie cart_cookie = null;
for (Cookie cookie : cookies) {
if ("cart".equals(cookie.getName())) { //获取购物车cookie
cart_cookie = cookie;
}
}
return cart_cookie;
}
获取Cookie中的购物车列表
/** * 获取cookie中的购物车列表 * * @param response * @param request * @return 购物车列表 * @throws UnsupportedEncodingException 抛出异常 */ public List<CartVo> getCartInCookie(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException { // 定义空的购物车列表 List<CartVo> items = new ArrayList<CartVo>(); String value_1st = ""; // 购物cookie Cookie cart_cookie = getCookie(request); // 判断cookie是否为空 if (cart_cookie != null) { // 获取cookie中String类型的value value_1st = URLDecoder.decode(cart_cookie.getValue(), "utf-8");//从cookie获取购物车 // 判断value是否为空或者""字符串 if (value_1st != null && !"".equals(value_1st)) { // 解析字符串中的数据为对象并封装至list中返回给上一级 String[] arr_1st = value_1st.split("=="); for (String value_2st : arr_1st) { String[] arr_2st = value_2st.split("="); CartVo item = new CartVo(); item.setGoodsId(Integer.parseInt(arr_2st[0])); //商品id item.setGoodsTypeId(Integer.parseInt(arr_2st[1])); //商品类型ID item.setGoodsName(arr_2st[2]); //商品名 item.setGoodsPrice(Integer.parseInt(arr_2st[3])); //商品市场价格 item.setGoodsDiscount(Integer.parseInt(arr_2st[4]));//商品折后价格 item.setGoodsNum(Integer.parseInt(arr_2st[5]));//商品月销量 item.setGoodsInfo(arr_2st[6]);//商品详情 item.setNum(Integer.parseInt(arr_2st[7]));//加入购物车数量 items.add(item); } } } return items;
}
制作cookie所需value
/**
* 制作cookie所需value
*
* @param cartVos 购物车列表
* @return 解析为字符串的购物车列表,属性间使用"="相隔,对象间使用"=="相隔
*/
public String makeCookieValue(List<CartVo> cartVos) {
StringBuffer buffer_2st = new StringBuffer();
for (CartVo item : cartVos) {
buffer_2st.append(item.getGoodsId() + "=" + item.getGoodsTypeId() + "=" + item.getGoodsName() + "="
+ item.getGoodsPrice() + "=" + item.getGoodsDiscount() + "=" + item.getGoodsNum() + "=" + item
.getGoodsInfo() + "=" + item.getNum() + "==");
}
return buffer_2st.toString().substring(0, buffer_2st.toString().length() - 2);
}