Thursday, July 3, 2008

Google Web Toolkit - RPC Call

This post will document how to make a RPC call using the Google Web Toolkit.

For a more detailed walk through of the Google Web Toolkit I recommend this book: Google Web Toolkit Applications

To sum it up you must create 1 class and 2 interfaces.

1) Service Interface that extends RemoteService and defines the methods for your service
2) Asynchrounous interface which is a similar to the the above except:
** doesn't extend RemoteService
** all method return void
** one extra AsyncCallBack parameter to each defined method
3) Your actual service which extends RemoteServiceServlet and implements your interface created in step (1)
** This should be a servlet and mapped properly in your web.xml

The two interfaces will need to be in the com.ciient package, and the service in the com.server or on someother url on the same host where this will be deployed.

So on to the code.

First the interfaces and classes, following by a sample app that calls it:


package com.client.time;
public interface ITimeService extends RemoteService {
public Date getDate();
}

package com.client.time;
public interface ITimeServiceAsync {
public void getDate(AsyncCallback callback);
}

package com.server.time;
public class TimeService extends RemoteServiceServlet implements ITimeService {

public Date getDate() {
return new Date();
}
}

public void loadDate(final Label label) {
ITimeServiceAsync timeService = (ITimeServiceAsync) GWT.create(ITimeService.class);


ServiceDefTarget endpoint = (ServiceDefTarget) timeService;
endpoint.setServiceEntryPoint("/GWT/TimeService");

AsyncCallback callback = new AsyncCallback() {

public void onSuccess(Object result) {
label.setText(result.toString());
}

public void onFailure(Throwable caught) {
label.setText("failure" + caught.getMessage());
}
};

label.setText("pending");
timeService.getDate(callback);

}

No comments: