简体   繁体   English

序列化对象并将其作为字符串存储在Cookie中

[英]Serialize object and store it as string in cookie

I am java spring mvc developer I have an object and i want to store it in cookie but I dont know how to serialize the object to save it someone can help me? 我是java spring mvc开发人员,我有一个对象,我想将其存储在cookie中,但我不知道如何序列化对象以保存它,有人可以帮助我吗? or can suggest other idea to store object in cookie? 或可以建议其他想法来将对象存储在Cookie中?

Size of a cookie could be max 4Mb. Cookie的最大大小为4Mb。 This might not be veryusefull for storing objects. 这对于存储对象可能不是非常有用。 You should consider using HTML5 storage as an alternative. 您应该考虑使用HTML5存储作为替代方案。

You can story the object in any String format you want in the cookie. 您可以在Cookie中以所需的任何字符串格式为对象添加故事。

Build a custom toString() and constructor from String for your object. 使用String为您的对象构建自定义的toString()和构造函数。 Write to the cookie ojectToSave.toString() and when reading from the cookie construct objectToLoad = new MyObject(cookieString) . 写入cookie ojectToSave.toString()并从cookie构造中读取objectToLoad = new MyObject(cookieString)

Example

public class MyObject(){

    private String username;
    private int rank;
    private OtherObject otherObject;

    //Constructors,getters,setters,rest of class
    //...

    public MyObject(String s){
         this();
         //Trim class delimiter (  )
         String trimedStr = s.replaceAll("\(\\$", "").replaceAll("^\)\\", "");

         //parse string
         String[] components = trimedStr.split(",");
         this.username = components[0];
         this.rank     = Integer.valueOf(components[1]);
         //Otherobject should be constructed similar
         this.otherobject = new OtherObject(components[2]);
    }

    public String toString(){
        return "("+username+","+rank+","+otherObject.toString()+")";
    }
 }

I used "(",")" to separate an object, but it is not necessary. 我使用"(",")"来分隔一个对象,但这不是必需的。 If OtherObject contained 2 string values it would look like this: 如果OtherObject包含2个字符串值,它将看起来像这样:

(radu, 964 , ( string1 , string2 ) )

But if you do not have other objects, you can skip the "(",")" or simply store as just one list 但是,如果您没有其他对象,则可以跳过"(",")"或仅存储为一个列表

(radu, 964 , string1 , string2 )

and have this.otherobject = new OtherObject(components[2],components[3]); 并具有this.otherobject = new OtherObject(components[2],components[3]);

Use JSON format and Jackson to not have to build the string format yourself (and modify it everytime your change the object class definition) 使用JSON格式和Jackson不必自己构建字符串格式(并在每次更改对象类定义时进行修改)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM