Fancy UI

All About Crazy IT Stuff

Cross site requests with GWT, RestyGWT and HTML5 CORS

with 4 comments

I’m working on a GWT project that can be added to any web site to load a banner and to do that, I had to make some requests to a REST service deployed on another server.

We all know that this is impossible because Cross Site requests are forbidden, but with the introduction of CORS in HTML5 this can be done (check http://www.html5rocks.com/en/tutorials/cors/ for more details), on this article I’m going to show how to make CORS requests to a REST services with RestyGWT and GWTP for testing I used Jersey as REST service provider (this can be any other framework : RestEasy, Rails…).

First of all, in all modern browsers today, when you execute a Cross Site request they automatically send a CORS request (or a Preflight request with the value OPTION in the header), your backend service should respond to this with an empty response containing some required headers to allow the CORS (we can compare this step to the Handshake in TCP), after receiving the correct response the browser will execute the actual request you want to send.

Enabling CORS on the back end :

To enable CORS on my JAX-RS REST service, I added a preflight response for each REST method, the response contain the required headers to authorize the request, I also added the same headers to the final response.

@Path("/mydata")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)

public class MyRestService {
  @Context
  private HttpServletResponse response;

  @Inject
  private final MyDao myDao;

  @OPTIONS
  @Path("/{id}") //The response for the preflight request made implicitly by the bowser
  public Response getByIdPreflight() {
    return Response.ok()
      .header("Access-Control-Allow-Origin", "*")
      .header("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS")
      .header("Access-Control-Allow-Headers", "x-http-method-override").build();
  }

  @GET
  @Path("/{id}")
  public MyData getById(@PathParam("id") long id) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
    response.addHeader("Access-Control-Allow-Headers", "x-http-method-override");

    MyData data = myDao.get(id);
    return data;
  }
}

You can also use a third party library to enable CORS on your java back end like for example : http://software.dzhuvinov.com/cors-filter.html.

Doing a CORS request from RestyGWT :

RestyGWT is a rich REST client API for GWT, it is based upon the JAX-RS annotation, for the given service in the back end, we have to write an interface containing all method we want to call on server (if you are not familiar with RestyGWT please visit : http://goo.gl/MKw6l).

public interface MyDataService extends RestService {
  @GET
  @Path("/promotions/{id}")
  @Consumes(MediaType.APPLICATION_JSON)
  public void getById(@PathParam("id") long id, MethodCallback<MyData> callback);
}

To bind and configure this interface service to the actual service on the back end, I register it as a Singleton bean on my GIN module.

public class ClientModule extends AbstractPresenterModule {
  @Override
  protected void configure() {
    install(new DefaultModule(ClientPlaceManager.class));
    bindConstant().annotatedWith(Names.named("rest")).to("http://myremoteapp.com/services");
  }

  @Provides
  @Singleton
  @Inject
  public MyDataService provideMyDataService(@Named("rest") String url) {
    MyDataService myDataService = GWT.create(MyDataService.class);
    Resource resource = new Resource(url);
    ((RestServiceProxy) myDataService).setResource(resource);
    return myDataService;
  }
}

And finally, to use this service you just need to inject it in your presenter and use it normally. That’s it for this article 😀

Advertisements

Written by imrabti

August 8, 2012 at 7:33 am

Posted in GWT

Tagged with , , , ,

4 Responses

Subscribe to comments with RSS.

  1. Your means of describing the whole thing in this article is
    actually fastidious, every one be able to simply understand it,
    Thanks a lot.

    stopping smoking cigarettes

    October 20, 2012 at 4:44 am

  2. It’s not clear what is AbstractPresenterModule / DefaultModule and Resource. Are these custom classes from your project?

    jdevelop

    November 2, 2012 at 3:24 pm

    • The classes are from the framework GWTP.

      imrabti

      November 2, 2012 at 3:54 pm

      • Okay, perhaps you could advice how to create and bind the module with GWT? I guess only registration part is needed, and install method is not?

        jdevelop

        November 2, 2012 at 4:28 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: