HTML5 Zone is brought to you in partnership with:

Software engineer, working at ArcBees. A heavy GWT / Java / Spring developer. Mrabti is a DZone MVB and is not an employee of DZone and has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Cross Site Requests With GWT, RestyGWT and HTML5 CORS

08.14.2012
| 9089 views |
  • submit to reddit

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 :-D

Published at DZone with permission of Mrabti Idriss, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)