【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

相关文章
相关标签/搜索