用Cookie实现购物车

首先准备两张数据表:

1.  tb_customer(用户表)

··用Cookie实现购物车2. tb_orderitem(购物车表)

用Cookie实现购物车

用cookie实现购物车,可以减小数据库的压力,不用每一次用户查看购物车都是从数据库中获取。为了保持cookie中的购物车和数据库中的购物车数据相同,

应该是把cookie中购物车的数据和数据库中购物车的数据保持同步。

1. 添加商品到购物车

    从cookie中获取该用户的购物车,如果该用户购物车为空,则从数据库中获取购物车,再把购物车封装到cookie中。添加商品到购物车,首先判断该商品是否存在购物当中,

   存在,则修改该商品的购买数量,然后修改该商品在cookie中和数据库中的数量。不存在,则新添加一个商品到cookie和数据库中。

2.删除单个商品

  从cookie中获取出购物车,然后遍历购物车中商品,判断要删除商品是否在购物车中,存在,则删除该商品(指的是在cookie和数据库中删除该商品),更新cookie中的购物车。如果从cookie中获取不到购物车(可能是cookie失效了,或者是用户清除掉了cookie),这种清况下可以从数据库中获取出该用户的购物车,再进行删除指定商品,最后封装购物车到cookie。

3.清空购物车

    删除该用户购物车cookie,删除该用户数据库中购物车数据。

实现代码:

添加商品:
/**
	 * @author Michael
	 * 添加商品到购物车
	 */
	@Override
	public String add() throws Exception {
		if(productId != null && productId > 0){
			Customer customer = (Customer) session.get("customer");//获取当前用户
			List<OrderItem> items = new ArrayList<OrderItem>();
			StringBuffer buffer_2st = new StringBuffer();
			Cookie cookie_2st = null; 
			String value_3st = "";
			
			items = getCookieCart(); //从cookie获取购物车
			if(items.size() <= 0){//当用户从cookie获取不到购物车数据时,再从数据库中获取
				items = getDbShopCart();
			}
			Cookie cart_cookie = getShopCartCookie(); //获取购物车cookie
			
			// 标记添加的商品是否是同一件商品
				boolean flag = false;
				for(OrderItem item : items ){
					if(item.getProductId() == productId){
						item.setAmount(item.getAmount() + 1);// 购买相同的商品,更新数量
						flag = true;
						//更新数据库中该商品的数量
						String where = "where productId = ? and customer.id = ?";
						Object[] obejct = new Object[]{productId,customer.getId()};
						List<OrderItem> item_1st =  orderItemDao.find(-1, -1, where, obejct).getList();
						OrderItem item_2st = item_1st == null ? null:item_1st.get(0);
							
						if(item_2st != null){
							item_2st.setAmount(item_2st.getAmount()+ 1);
							orderItemDao.saveOrUpdate(item_2st);
						}
					}
				}
			
				if(!flag){
					OrderItem item_1st = new OrderItem();
					ProductInfo pro = productDao.load(productId);
					item_1st.setProductId(pro.getId());
					item_1st.setProductName(pro.getName());
					item_1st.setProductPrice(pro.getSellprice());
					item_1st.setProductMarketprice(pro.getMarketprice());
					item_1st.setCustomer(customer);
					items.add(item_1st);
					orderItemDao.save(item_1st);
				}
			
			//封装购物车数据到cookie中
			for(OrderItem item : items){
				buffer_2st.append(item.getProductId()+"="+item.getProductName()+"="+item.getProductPrice()+"="+item.getProductMarketprice()+"="+item.getAmount()+"==");
			}
			value_3st = buffer_2st.toString();
			
			if(value_3st != null && !"".equals(value_3st)){
				value_3st = value_3st.substring(0,value_3st.length() - 2);
				if(cart_cookie == null){
					//cookie名称是以每个用户的用户名和用户id组成,做到每一个用户都有一个自己cookie      URLEncoder.encode用来解决中文乱码问题
					cookie_2st = new Cookie(customer.getUsername()+customer.getId(),URLEncoder.encode(value_3st,"utf-8"));
					cookie_2st.setPath("/");//设置在该项目下都可以访问该cookie
					cookie_2st.setMaxAge(60*10);//设置cookie有效时间为10分钟
					ServletActionContext.getResponse().addCookie(cookie_2st);//添加cookie
				}else{
					cart_cookie.setValue(URLEncoder.encode(value_3st,"utf-8"));
					cart_cookie.setPath("/");
					cart_cookie.setMaxAge(60*10);
					ServletActionContext.getResponse().addCookie(cart_cookie);
				}
			}
		}
		return "shopCart";//会再次调用list方法(已经在strut2配置文件中 配置了)

	}

从数据库中获取购物车
	/**
	 * 从数据库获取购物车
	 * @author Michael
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public List<OrderItem> getDbShopCart() throws UnsupportedEncodingException{
		Customer customer = (Customer) session.get("customer");
		String where  = "where customer.id = ?";
		Object[] object = new Object[]{customer.getId()};
		List<OrderItem> items = new ArrayList<OrderItem>();
		items = orderItemDao.find(-1, -1, where, object).getList();
		if(items.size() > 0){
			padCookie(items); //把购物车封装到cookie中
		}
		return items;
	}


从cookie中获取购物车

	/**
	 * 从cookie获取购物车
	 * @author Michael
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public List<OrderItem> getCookieCart() throws UnsupportedEncodingException{
		
		List<OrderItem> items = new ArrayList<OrderItem>();
		String value_1st = "";
		Cookie cart_cookie = getShopCartCookie();//获取当前用户购物车cookie
		
		if(cart_cookie != null){
			value_1st = URLDecoder.decode(cart_cookie.getValue(),"utf-8");//从cookie获取购物车
			if(value_1st != null && !"".equals(value_1st)){
				String[] arr_1st = value_1st.split("==");
				for(String value_2st : arr_1st){
					String[] arr_2st = value_2st.split("=");
					OrderItem item = new OrderItem();
					item.setProductId(Integer.parseInt(arr_2st[0])); //商品id
					item.setProductName(arr_2st[1]); //商品名称
					item.setProductPrice(Float.valueOf(arr_2st[2])); //商品销售价格
					item.setProductMarketprice(Float.valueOf(arr_2st[3])); //商品市场价格
					item.setAmount(Integer.parseInt(arr_2st[4]));//商品数量
					items.add(item);
				}
			}
		}
		return items;
	}

获取当前用户购物车cookie

/**
	 * 获取当前用户购物车cookie
	 * @author Michael
	 * @return
	 */
	public Cookie getShopCartCookie(){
		Customer customer = (Customer) session.get("customer");
		Cookie cart_cookie = null;
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		for(Cookie cookie : cookies){
			if((customer.getUsername()+customer.getId()).equals(cookie.getName())){ //获取购物车cookie
				cart_cookie = cookie;
			}
		}
		return cart_cookie;
	}

查看购物车

	/**
	 * 查看购物车
	 * @author Michael
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		List<OrderItem> items = new ArrayList<OrderItem>();
		items = getCookieCart(); //从cookie获取购物车
		if(items.size() <= 0){ //从cookie获取购物车中数据为空时,再调用数据库获取购物车的方法
			items = getDbShopCart();
		}
		ServletActionContext.getRequest().removeAttribute("cart");
		ServletActionContext.getRequest().getSession().setAttribute("cart",items); //保存到session中 在页面用来展示
		return LIST;//返回购物车页面
	}

填充购物车数据到cookie中

/**
	 * 填充购物车数据到cookie中
	 * @author Michael 
	 * @throws UnsupportedEncodingException 
	 */
	public void padCookie(List<OrderItem> items) throws UnsupportedEncodingException{
		Customer customer = (Customer) session.get("customer");
		StringBuffer buffer = new StringBuffer();
		String value_4st = "";
		
		Cookie cookie = getShopCartCookie();
		if(cookie != null){
			cookie.setMaxAge(0);
			cookie.setPath("/");
			ServletActionContext.getResponse().addCookie(cookie);
		}
		
		for(OrderItem item : items){
			buffer.append(item.getProductId()+"="+item.getProductName()+"="+item.getProductPrice()+"="+item.getProductMarketprice()+"="+item.getAmount()+"==");
		}
		value_4st = buffer.toString();
		
		if(value_4st != null && !"".equals(value_4st)){
			value_4st = value_4st.substring(0,value_4st.length() - 2);
			Cookie cookie_2st = new Cookie(customer.getUsername()+customer.getId(),URLEncoder.encode(value_4st,"utf-8"));
			cookie_2st.setPath("/");
			cookie_2st.setMaxAge(60*10);
			ServletActionContext.getResponse().addCookie(cookie_2st);
		}
	}

删除购物车中指定的商品

/**
	 * 删除购物车中指定的商品
	 * @author Michael
	 * @return
	 * @throws Exception
	 */
	public String delete() throws Exception {
		List<OrderItem> items_1st = getCookieCart(); //从cookie获取购物车
		OrderItem d_item = null;
		for(OrderItem item : items_1st){ //删除指定的商品
			if(item.getProductId() == productId){
				orderItemDao.deleteByPid(productId);
				d_item = item;
			}
		}
		
		if(d_item != null && items_1st != null){
			items_1st.remove(d_item);
		}
		
		if(items_1st.size() > 0){
			padCookie(items_1st); //封装购物车到cookie
		}else{
			List<OrderItem> items = getDbShopCart();
			for(OrderItem item : items){
				if(item.getProductId() == productId){
					orderItemDao.delete(item.getId());
					d_item = item;
				}
			}
			items.remove(d_item);
			padCookie(items);
		}
		return "shopCart";//会再次调用list方法(已经在strust2配置文件中 配置了)
	}

清空购物车

/**
	 * 清空购物车
	 * @author Michael
	 * @return
	 * @throws Exception
	 */
	public String clear() throws Exception {
		List<OrderItem> items = getDbShopCart();
		for(OrderItem item : items){
			orderItemDao.delete(item.getId());
		}
		
		Cookie cart_cookie = getShopCartCookie();
		if(cart_cookie != null){
			cart_cookie.setMaxAge(0);//删除cookie
			cart_cookie.setPath("/");
			ServletActionContext.getResponse().addCookie(cart_cookie);
		}
		ServletActionContext.getRequest().removeAttribute("cart");
		return "shopCart";//会再次调用list方法(已经在strut2配置文件中 配置了)
	}


欢迎各位评论,指出不足之处,如果你们有更好的实现方式,也可以共享一下。

用Cookie实现购物车

(0)
(0)
   
举报
评论 一句话评论(0
上一篇:Xcode5 运行程序 提示“iOS 模拟器”未能安装此应用程序


下一篇:替换空格算法