RestyGWTを使う、その2

RestyGWTを使う、その1の続きである。

RestyGWTライブラリを依存に入れる。

RestyGWTを追加する。

dependencies {
  compile group: 'com.google.gwt', name: 'gwt-dev', version: '2.8.2'
  compile group: 'com.google.gwt', name: 'gwt-user', version: '2.8.2'


  compile group: 'javax.ws.rs', name: 'javax.ws.rs-api', version: '2.1.1'
  compile group: 'org.glassfish.jersey.containers', name: 'jersey-container-servlet', version: '2.29'
  compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.29'
  compile group: 'com.fasterxml.jackson.jaxrs', name: 'jackson-jaxrs-json-provider', version: '2.9.9'  
  compile group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.29'  

  // 追加
  compile group: 'org.fusesource.restygwt', name: 'restygwt', version: '2.2.4' 
}

gwt.xmlに以下を追加する。

<inherits name="org.fusesource.restygwt.RestyGWT"/>

サービスクライアントを作成する

このサービスを呼び出すクライアントを作成する。

package sample.client;

import java.util.*;
import javax.ws.rs.*;
import org.fusesource.restygwt.client.*;
import sample.shared.*;

@Path("/api/thing")
public interface ThingClient extends RestService {
  @GET
  public void getThings(MethodCallback<List<Thing>> callback);

  @GET
  @Path("/{id}")
  public void getThing(@PathParam("id") String id, MethodCallback<Thing> callback);
}

クライアントコードを変更する

元からあるsample.client.Sampleにコードを追加する。ボタンが押されたらREST-APIを呼び出すように改造する。

以下を追加

public class Sample implements EntryPoint {

  .....
  .....
  .....

  static ThingClient client = GWT.create(ThingClient.class);

  private void testit() {
    MethodCallback<List<Thing>> callback = new MethodCallback<List<Thing>>() {
      @Override
      public void onFailure(Method method, Throwable caught) {

      }

      @Override
      public void onSuccess(Method method, List<Thing> result) {
        GWT.log("" + result);
      }
    };

    Defaults.setServiceRoot(GWT.getHostPageBaseURL());
    client.getThings(callback);
  }
}

ボタンクリック時に、元のGWT-RPC呼び出しとともにRESTを呼び出してみる。

      /**
       * Fired when the user clicks on the sendButton.
       */
      public void onClick(ClickEvent event) {
        testit(); // これを追加
        sendNameToServer();
      }

ブラウザ開発ツールのコンソールを見てみると、たしかにオブジェクトが3つ取得されている。