三种方式Session 、cookie等 数据库
添加购物车首页界面
shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车
按钮
我的购物车
XML配置
成功效果
清空购物车package com.hmf.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmf.entity.User;
import com.hmf.vo.ShoppingVo;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.StringUtils;public class ShoppingAction extends ActionSupport implements ModelDriver
{
private ShoppingVo vo=new ShoppingVo();
public ShoppingVo getModel() {
return vo;
}
public String add(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session=req.getSession();
User cuser =(User) session.getAttribute("cuser");
ObjectMapper om=new ObjectMapper();
try {
if(cuser!=null) {
long uid=cuser.getId();
ListshopGoodsVos=null;
//从session取到购物车信息
String shopinginfo =(String) session.getAttribute("shopping_"+uid);
if(StringUtils.isNotBlank(shopinginfo)) {
shopGoodsVos=om.readValue(shopinginfo,List.class);
}else {
shopGoodsVos =new ArrayList();
}
//点击前台购物车信息商品内容
shopGoodsVos.add(vo);
session.setAttribute("shopping_"+uid,om.writevalueAsString(shopGoodsVos));
req.setAttribute("shopGoodsVos", shopGoodsVos);
}
}catch(Exception e) {
e.printStackTrace();
}
return "shoppingCar";
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session=req.getSession();
User cuser =(User) session.getAttribute("cuser");
ObjectMapper om=new ObjectMapper();
String shopinginfo= (String) session.getAttribute("shopping_"+cuser.getId());
try {
ListshopGoodsVos=om.readValue(shopinginfo,List.class);
req.setAttribute("shopinginfo", shopGoodsVos);
} catch (IOException e) {
e.printStackTrace();
}
return "shoppingCar";
}
public void clear(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session=req.getSession();
User cuser =(User) session.getAttribute("cuser");
session.removeAttribute("shopping_"+cuser.getId());
try {
ResponseUtil.writeJson(resp, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
拜拜拜



