Wednesday, March 3, 2010

GWT Basics

Okay, let's do a simple GWT interaction to see how it works. Note that this will depend on data being in the datastore, data that the site doesn't have yet. I can just create a simple GWT call to populate the datastore so what we're developing can return some results.

The servlet model was a page load model. Each page load called a servlet, which returned the HTML to display. So when designing your servlet based site, you thought in terms of the pages the site needs to display.

The GWT model is a remote procedure call model. Picture the client and server both containing objects that talk to each other (primarily the client objects making calls on the server objects to get information). The application user interface itself is contained in the client, and looks more like a regular Java application than a web page.

So we have to shift our thinking from the servlet model. To identify GWT interactions, think about the sorts of information the client might need to get from the server.

I'll start with something simple. I want the front page of the site to display a list of contests. So that list of contests is information the client needs to get from the server.

Think of that client/server interaction as a method call between objects. Let's say that I just want that call to return the names of the current contests. I might write the method interface like this:


String[] getCurrentContests ();


To convert that into Java code for your project, click on the project.client package and choose File->New->Interface. Next to "Extended interfaces", click the Add button. Type in RemoteService and choose to add that interface.

Don't forget to give your interface a name. I'll name my interface something like Contests.

Click Finish and the interface stub is created. It should look something like this:


import com.google.gwt.user.client.rpc.RemoteService;

public interface Contests extends RemoteService
{

}


We want to add an annotation before the interface line to say what the URL path is on the server. It'll end up like this:


import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("getContests")
public interface Contests extends RemoteService
{

}


Now we need to add in the actual method interface:


import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("getContests")
public interface Contests extends RemoteService
{
String[] getCurrentContests ();
}


That's it for creating the interface. What we've defined is the interface between the client and server.

What we still need to define is what the client does to call this interface, and what the server does to implement it.

More next post.