Session对象的序列化和反序列化

前言:有时小刘想将session存储到数据库中,用作持久化,例如app的用户登录状态实现。不仅是session,其他对象都是可以使用以下方法实现

 session的序列化和反序列化


    /**
     * 
     * 机能概要:将Session序列化成String类型
     *
     * @param session
     * @return
     */
    public static byte[] serializ(Session session) {
        try {
            //ByteArrayOutputStream 用于存储序列化的Session对象
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            //将Object对象输出成byte数据
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(session);

            //将字节码,编码成String类型数据
//            return Base64.getEncoder().encodeToString(bos.toByteArray());
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("序列化失败");
        }
    }


    /**
     * 
     * 机能概要:将一个Session的字符串序列化成字符串,反序列化
     *
     * @param sessionStr
     * @return
     */
    public static Session deserializ(byte[] sessionStr) {
        try {
            //读取字节码表
//            ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(sessionStr));
            ByteArrayInputStream bis = new ByteArrayInputStream(sessionStr);
            //将字节码反序列化成 对象
            ObjectInputStream in = new ObjectInputStream(bis);
            Session session = (Session) in.readObject();
            return session;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("反序列化失败");
        }
    }

如有不解,请加java爱好群大家交流:852665736;群里都是热心好客的小伙伴,大家一同进步。

无偿免费分享源码以及技术和面试文档,更多优秀精致的源码技术栈分享请关注微信公众号:gh_817962068649 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值