前几天写了一段把购物车放入Cookie的 代码,采用的是把整个购物车对象序列化为字符串放入Cookie进行存取的方式,现把部分代码共享一下,供大家参考。
存储代码:
private void saveCartToCookie(Cart cart) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(cart);
String cookieValue = baos.toString("ISO-8859-1");
String encodedCookieValue = java.net.URLEncoder.encode(cookieValue,
"UTF-8");
Cookie cookie = new Cookie(CART_COOKIE_FLAG, encodedCookieValue);
cookie.setSecure(false);
cookie.setPath(getCartCookiePath());
cookie.setMaxAge(COOKIE_MAX_AGE);
getResponse().addCookie(cookie);
} catch (Exception e) {
log.error("保存购物车到cookie出错:" + e.getMessage());
}
}
读取代码:
private Cart getCartFromCookie() {
Cookie cookie = getCartCookie();
if (cookie == null) {
return null;
}
String cookieValue = cookie.getValue();
if (StringUtils.isEmpty(cookieValue))
return null;
try {
String decoderCookieValue = java.net.URLDecoder.decode(cookieValue,
"UTF-8");
Cart result = new Cart();
ByteArrayInputStream bais = new ByteArrayInputStream(cookieValue
.getBytes("ISO-8859-1"));
ObjectInputStream ios = new ObjectInputStream(bais);
result = (Cart) ios.readObject();
return result;
} catch (Exception e) {
log.error("从cookie中解析购物车出错:" + e.getMessage());
return null;
}
}
在序列化时主要是要注意两个部分,首先是先把序列化的字节流转换为ISO-8859-1编码方式的字符串,然后就是再把该字符串编码为UTF-8格式进行传输。
使用以上方法,还可以把对象序列化为字符串放到XML中进行存取。