如何把对象序列化为字符串进行WEB传输
来源:互联网 发布:战争雷霆淘宝代码 编辑:程序博客网 时间:2024/06/01 19:37
前几天写了一段把购物车放入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中进行存取。
- 如何把对象序列化为字符串进行WEB传输
- 如何把对象序列化为字符串进行WEB传输
- C#如何把类CLASS实例进行序列化及反序列化为XML文件
- js对象序列化为json字符串
- 将对象序列化为XML字符串
- 如何把异常信息格式化为字符串
- 使用 XStream 把 Java 对象序列化为 XML
- 使用XStream把Java对象序列化为XML
- 使用 XStream 把 Java 对象序列化为 XML
- 使用XStream把Java 对象序列化为XML!!!
- 使用 XStream 把 Java 对象序列化为 XML
- 使用 XStream 把 Java 对象序列化为 XML
- 使用 XStream 把 Java 对象序列化为 XML
- 使用 XStream 把 Java 对象序列化为 XML
- 把对象序列化为xml格式和反序列化
- c#将对象序列化为字符串和将字符串反序列化为对象
- c#将对象序列化为字符串和将字符串反序列化为对象
- 把流转化为字符串
- 如何使用代理帐号下载Android源代码
- JavaScript 比较和逻辑运算符
- JS动态调用函数的方式
- ch02 hello
- 敏捷开发中编写高质量Java代码---转
- 如何把对象序列化为字符串进行WEB传输
- JavaScript If...Else 语句
- sfc_os.dll第五号函数替换文件
- 混合高斯背景建模
- 地图上2不同区域内的路网存储过程
- Jquery 投票插件
- Milan Serie A 2 crack chasing prey before he is the world's No. 1 star
- 关于QT 中 QDialog的几点疑问的解答
- structs1.2 对于图片上传的处理