下面是把把整个购物车对象序列化为字符串放入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格式进行 传输。