【java】Cookie購物車實現

前言

一個基於Cookie的購物車實現
話很少說,直接上代碼
java


導包

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

製做cookie須要的value

public static String makeCookieValue(List<購物車POJO> pojos, 購物車POJO pojo) {
		JSONArray array = new JSONArray();
		if (pojos.size() <= 0) {
			JSONObject json = new JSONObject();
			json.put("key", pojo.getXX());
			array.add(json);
		} else {
			List<Integer> ids = new ArrayList<Integer>();
			for (購物車pojo item : pojos) {
				JSONObject json = new JSONObject();
				json.put("key", pojo.getXX());
				array.add(json);
				ids.add(item.getId());
			}
			if (!ids.contains(pojo.getId())) {//新添加進來的產品信息若是購物車中已存在就不進行重封裝
				JSONObject json = new JSONObject();
				json.put("key", pojo.getXX());
				array.add(json);
			}
		}
		return array.toString();
	}
	//購物車商品從新封裝
	public static String makeCookieValue(List<Cart> cart) {
		JSONArray array = new JSONArray();
		for (Cart item : cart) {
			JSONObject json = new JSONObject();
			json.put("id", item.getId());
			json.put("name", item.getName());
			json.put("fileName", item.getFileName());
			json.put("price", item.getPrice());
			json.put("num", item.getNum());
			array.add(json);
		}
		return array.toString();
	}

獲取名爲cart的購物車

public static 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中的購物車列表

public static List<購物車POJO> getCartInCookie(HttpServletResponse response, HttpServletRequest request)throws UnsupportedEncodingException {
		// 定義空的購物車列表
		List<購物車POJO> items = new ArrayList<購物車POJO>();
		String value = "";
		// 購物cookie
		Cookie cart_cookie = getCookie(request);
		// 判斷cookie是否爲空
		if (cart_cookie != null) {
			// 獲取cookie中String類型的value
			value = URLDecoder.decode(cart_cookie.getValue(), "utf-8");// 從cookie獲取購物車
			// 判斷value是否爲空或者""字符串
			if (value != null && !"".equals(value)) {
				JSONArray array = JSONArray.fromObject(value);
				// 解析字符串中的數據爲對象並封裝至list中返回給上一級
				for (int i = 0; i < array.size(); i++) {
					JSONObject json = JSONObject.fromObject(array.get(i));
					購物車POJO pojo = new 購物車POJO();
					pojo.setXX(json.get("key"));
					items.add(cartVo);
				}
			}
		}
		return items;
	}

添加商品到購物車

public void addCart(){
        try {
            //獲取cookie中購物車
			List<購物車POJO> pojos = getCartInCookie(response, request);
			Cookie cookie;
			// 若是購物車列表爲空
			if (pojos.size() <= 0) {
				// 將當前傳來的商品添加到購物車列表
				//若是cookie中沒有名爲cart的key
				if (getCookie(request) == null) {
					// 製做購物車cookie數據
					cookie = new Cookie("cart",URLEncoder.encode(makeCookieValue(pojos, 購物車POJO), "utf-8"));
					cookie.setPath("/");// 設置在該項目下均可以訪問該cookie
					cookie.setMaxAge(60 * 30);// 設置cookie有效時間爲30分鐘
					response.addCookie(cookie);// 添加cookie
				} else {
					cookie = getCookie(request);
					cookie_2st.setPath("/");// 設置在該項目下均可以訪問該cookie
					cookie_2st.setMaxAge(60 * 30);// 設置cookie有效時間爲30分鐘
					cookie_2st.setValue(URLEncoder.encode(makeCookieValue(pojos, 購物車POJO)));
					response.addCookie(cookie);// 添加cookie
				}
			}
			// 當獲取的購物車列表不爲空時
			else {
				for (購物車POJO pojo : pojos) {
					// 若是購物車中存在該商品則數量+1
					if (pojo.getId() == id) {
						pojo.setNum(pojo.getNum() + 1);
						break;
					}
				}
				// 獲取名爲"cart"的cookie
				cookie = getCookie(request);
				cookie.setPath("/");// 設置在該項目下均可以訪問該cookie
				cookie.setMaxAge(60 * 30);// 設置cookie有效時間爲30分鐘
				String value = CartUtil.makeCookieValue(pojos, 購物車POJO);
				cookie.setValue(URLEncoder.encode(value)); // 設置value
				response.addCookie(cookie);
			}
		} catch (UnsupportedEncodingException e) {
		}
	}

從購物車刪除商品

public void delCartById(){
        HttpServletRequest request = ServletActionContext.getRequest();
    	HttpServletResponse response = ServletActionContext.getResponse();
    	try {
    		List<購物車POJO> pojoss = CartUtil.getCartInCookie(response, request);
    		List<購物車POJO> pojos=new ArrayList<購物車POJO>();
    		for(購物車POJO pojo:pojoss){
    			if(pojo.getId()!=id){
    				購物車POJO vo=new 購物車POJO();
    				vo=pojo;
    				pojos.add(vo);
    			}
    		}
    		Cookie cookie = CartUtil.getCookie(request);
    		cookie.setPath("/");// 設置在該項目下均可以訪問該cookie
    		cookie.setMaxAge(60 * 30);// 設置cookie有效時間爲30分鐘
    		String value = makeCookieValue(carts);
    		cookie_2st.setValue(URLEncoder.encode(value)); // 設置value
    		response.addCookie(cookie);
    	} catch (UnsupportedEncodingException e) {
    	}
    }

修改購物車商品

public void changeCart(){
        HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			List<購物車POJO> cartVos = getCartInCookie(response, request);
			List<購物車POJO> carts = new ArrayList<購物車POJO>();
            //減小
			if (type.equals("0")) {
				for (購物車POJO cartVo : cartVos) {
					if (cartVo.getId() == id) {
						購物車POJO cart = new 購物車POJO();
						cart.setId(id);
						cart.setNum(num - 1);
						carts.add(cart);
					} else {
						購物車POJO cart = new 購物車POJO();
						cart = cartVo;
						carts.add(cart);
					}
				}
				//增長
			} else if (type.equals("1")) {
				for (購物車POJO cartVo : cartVos) {
					if (cartVo.getId() == id) {
						購物車POJO cart = new 購物車POJO();
						cart.setId(id);
						cart.setNum(num + 1);
						carts.add(cart);
					} else {
						購物車POJO cart = new 購物車POJO();
						cart = cartVo;
						carts.add(cart);
					}
				}
			}
			Cookie cookie = getCookie(request);
			cookie.setPath("/");// 設置在該項目下均可以訪問該cookie
			cookie.setMaxAge(60 * 30);// 設置cookie有效時間爲30分鐘
			String value = makeCookieValue(carts, POJO);
			cookie.setValue(URLEncoder.encode(value)); // 設置value
			response.addCookie(cookie);
		} catch (Exception e) {
		}
	}

此代碼沒法直接使用,如需使用請更改代碼內相關變量json