Serializing objects in GWT and deserializing them in servlet
Our application is based on GWT and it generates various kinds of reports. These reports can be very big and we have noticed the problem with the GWT. In case if we return the generated report via asynchronous method – application becomes incredibly slow. So at some point we had to implement the following architecture:
- Submit DTO(it can be very-very complex) via async service
- Open new window with the url pointing to the servlet. This servlet gets this DTO, generates content and writes it into output with all required data.
However at some point this approach became unsuitable for some reasons. So we’ve started thinking of combining these requests into a single one.
At first I’ve tried three approaches of JSON serialization:
- Native GWT approach. It required changing lots of code.
- gwt-jsonizer. It seems like this library is rather obsolete. At least I couldn’t make it work with the GWT 1.7.1
- Rocket. This library worked rather fine, but it required lots of changes too. You’ll need to annotate every field you want to serialize with the speciial annotations.
So JSON approach required too much coding. Finally I realized that GWT itself serializes objects and started looking into this direction. So the idea is:
- Serialize object on the client side
- Pass the object as the parameter in the servlet
- Deserialize object in servlet
And this approach worked really fine.
// Creating factory. Interface of any remote service can be used
SerializationStreamFactory factory = (SerializationStreamFactory)GWT.create(ReportGeneratorService.class);
// Creating stream writer
SerializationStreamWriter writer = factory.createStreamWriter();
// Serializing object
// Getting serialized object content
String content = writer.toString();
The serialized object has a readable format. I haven’t found any more or less detailed description of this format. But debugging of the server side GWT code made this format pretty clear to me.
So now we have to deserialize DTO on the servlet side. It’s rather trivial.
// Getting parameter from request
String content = request.getParameter(“content”);
// Initializing stream reader
ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(
// Filling stream reader with data
// Reading deserialized object from the stream
dto = (D) streamReader.readObject();
So now we have deserialized object. That’s exactly what we want to have.
I’ve experienced problems with serialization with several existing DTOs and had to make some additional changes to them:
- Make them implementing com.google.gwt.user.client.rpc.IsSerializable interface. Please note that is you’re using enums, like we do, you’ll also add IsSerializable interface for every enum used
- Add serialVersionUID fields