如何把对象序列化为字符串进行WEB传输

本文分享了将购物车对象序列化为字符串并存入Cookie的方法。通过编码转换确保数据正确传输,适用于需要临时存储购物车信息的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前几天写了一段把购物车放入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中进行存取。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值