注意:因为在java中cookie里面是不能直接存放对象的,需要将对象序列化成json,再放入cookie中。字符串是可以直接放在cookie中的。本文中购物车是一个对象,所以要借助工具,序列化成json再放入购物车中。
第一步:导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar(这两个是springmvc支持的jar)及其他jar
第二步:java代码如下(导入的包部分省略,关键的导包有说明)
@Controller
public class CartController {
public static final Logger log = LoggerFactory.getLogger(CartController.class);
//购买按钮
@RequestMapping(value = "/shopping/buyCart.shtml")
public String buyCart(Integer skuId,Integer amount,Integer buyLimit,Integer productId,HttpServletRequest request ,HttpServletResponse response,ModelMap model){
//第一步:Sku
//springmvc
/**
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.springframework.beans.factory.annotation.Autowired;*/
ObjectMapper om = new ObjectMapper();
om.setSerializationInclusion(Inclusion.NON_NULL);
//声明
BuyCart buyCart = null;
//判断Cookie是否有购物车
//buyCart_cookie
Cookie[] cookies = request.getCookies();//获取cookie
if(null != cookies && cookies.length >0){
for(Cookie c : cookies){
if(Constants.BUYCART_COOKIE.equals(c.getName())){
//如果有了就使用此购物车
String value = c.getValue();//
try {
buyCart = om.readValue(value, BuyCart.class);
} catch (Exception e) {
log.error("出错了",e);
}
break;
}
}
}
//如果没有 创建购物车
if(null == buyCart){
//购物车 //最后一款
buyCart = new BuyCart();
}
if(null != skuId){
Sku sku = new Sku();
sku.setId(skuId);
//限制
if(null != buyLimit){
sku.setSkuUpperLimit(buyLimit);
}
//创建购物项
BuyItem buyItem = new BuyItem();
buyItem.setSku(sku);
//数量 1 2 3 -1
buyItem.setAmount(amount);
//添加购物项
buyCart.addItem(buyItem);
//最后一款商品的ID
if(null != productId){
buyCart.setProductId(productId);
}
//流
StringWriter str = new StringWriter();
//对象转Json 写的过程 Json是字符串流
try {
om.writeValue(str, buyCart);
} catch (Exception e) {
log.error("出错了",e);
}
//购物车装进Cookie中 对象转Json import javax.servlet.http.Cookie;
Cookie cookie = new Cookie(Constants.BUYCART_COOKIE,str.toString());
//关闭浏览器 也要有Cookie
//默认是 -1 关闭浏览器 就没了
//消灭 0 马上就没有
//expiry 秒
cookie.setMaxAge(60*60*24);
//路径
///shopping/buyCart.shtml
//默认 /shopping
// /shopping
// /buyer/*.shtml
cookie.setPath("/");
//发送
response.addCookie(cookie);
}
//装购物车装满
List<BuyItem> items = buyCart.getItems();
for(BuyItem item : items){
Sku s = skuService.getSkuByKey(item.getSku().getId());
item.setSku(s);
//小计
}
//小计
model.addAttribute("buyCart", buyCart);
return "product/cart";
}
//清空购物车,cookie失败的方法
@RequestMapping(value = "/shopping/clearCart.shtml")
public String clearCart(HttpServletRequest request,HttpServletResponse response){
Cookie cookie = new Cookie(Constants.BUYCART_COOKIE,null);
//关闭浏览器 也要有Cookie
//默认是 -1 关闭浏览器 就没了
//消灭 0 马上就没有
//expiry 秒 cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
return "redirect:/shopping/buyCart.shtml";
}
@Autowired
private SkuService skuService;
@Autowired
private AddrService addrService;
@Autowired
private SessionProvider sessionProvider;
}
申明:此文参考了创智播客新巴巴运动网的教学代码