用Cookie實現購物車
阿新 • • 發佈:2019-01-31
/** * @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配置檔案中 配置了)
}
歡迎各位評論,指出不足之處,如果你們有更好的實現方式,也可以共享一下。