mercredi 13 avril 2011

Elegant way of using REST services with GWT

With GWT it is very easy to call remote services asynchronously. To do this, simply use the GWT RPC mechanism.
However, this solution is not ideal, not in terms of design, but in terms of standard.
Indeed, the RPC mechanism is based on a proprietary data serialization. Even if the serialization format is open, it still proprietary and therefore not interoperable.
In contrast, REST is totally interoperable, but can put off when you are accustomed to the easy call to RPC services.
Well there is an API that brings together the best of both worlds. This little gem is called : restygwt.

At server-side, services are created with the implementation of your choice (for me jersey) : standard.
And at client-side interface, which contains the methods exposed by the REST service. This interface must inherit from the interface and use annotations RestService rest @ Path, @ POST, @ GET, @ PathParam ...

The interface methods should return void and take an extra parameter to handle the callback (MethodCallback ).

Then, simply instantiate the proxy for a rest service call as an RPC service with GWT.create (MyService.class).
The call is done the same way as an RPC service.

Here we see that the call to service rest is greatly simplified thanks to the powerful mechanism deffed binding.

Enjoy.