Thursday, June 7, 2012

Serializing and Deserializing an Object to a String

The other day I came across a scenario where I wanted to save the state a form was in so a returning user would find the form the way they left it. I wanted to store the form's state in HTML5 localstorage, but unfotunately, with the way our application is architected it didn't seem to be the cleanest solution. The next best option would be a cookie.
The advantage of using a cookie is that I can retrieve it from the HttpServletRequest object and all the processing can be done in one place. It also allows be to save a Java object directly as a string, however a cookie wasn't meant to store a lot of data so large objects might cause problems.
But, in order to store an object in a cookie it needs to be a String. To do that we serialize (the object must implement Serializable) and then base64 encode those bytes. Here is my implementation of serializing and deserializing a Java object.
And here is the reference to the original post from StackOverflow
And also for prosperity's sake, here is the prototype javascript to store values in HTML5 localStorage
It would then be enabled by calling WorkflowFormStorage.enabled("somekey"); Also note that the javascript is not a complete solution since there are some omitted pieces of code. It is just meant to give a rough idea of one way to do it.

1 comment:

  1. Thanks for sharing this unique and informative content which provided me the required information.
    Java Training in Chennai | JAVA Course in Chennai

    ReplyDelete