A tutorial on Remote Procedure Calls (RPCs) in Google Web Toolkit
At some point in your GWT development, you’ll want to start communicating with a server. Handily, GWT has a lot of stuff built in to help you do this in as easy a way as possible. The GWT RPC framework is very helpful indeed for just this, and this post will show you how to create your RPC services easily.
GWT is divided into “client-side” and “server-side” interaction. “Client-side” is what’s done by the browser, and “server-side” is obviously what’s being done by the server. Server-side is what can’t or shouldn’t be done in the browser. It helps to think of the client-side as the frontend and the server-side as the backend, though this isn’t always the correct view to take.
How to build a service into your GWT app:
This is a somewhat long one, so make yourself a cup (or seven cups) of coffee. Here’s the code for this tutorial, if you feel like just looking at code.
Make sure before you do this that you’re set up properly, with a blank project as detailed in this tutorial. However, the example that’s created by default makes use of RPCs, so if you just want a rough idea on how it works, have a look at that.
Alright, let’s get going.
First, let’s create the client-side interface to our service which lists all the RPC methods.
Right-click ie.flax.RPCTutorial.client (in my case) and select “New -> Interface”.
Call it something like “TestService”. “Service” at the end isn’t just a good naming convention, GWT is a little finicky with names. Services should end in “Service”, Asynchronous interfaces should end in ServiceAsync, the Server-side class should end in ServiceImpl.
Add com.google.gwt.user.client.rpc.RemoteService as an extended interface.
Now, you’ll see, there’s already an Error showing up in this interface. If you hover over the interface name, Eclipse will complain that it’s “Missing asynchronous interface TestServiceAsync”. Handily, Eclipse itself will fix this for you. If you place your cursor inside the name and press the Quick Fix hotkey (in my case, Command-1), it will come up with a variety of answers. We want the first one, because it’s easier than creating one yourself.
This has created an asynchronous interface for you. This contains the methods that you actually call from your code.
Next let’s create your method lists. We’ll simply get this to take in a number client-side, multiply it by two server-side, and log it, client-side. Easy-peasy. So, in TestService.java, throw in a method like so:
and in TestServiceAsync.java, a method like this:
Note that the Async version returns void and adds an AsyncCallback as an argument. This must be done for each method, depending on the type the method returns.
Lastly, add @RemoteServiceRelativePath(“test”) to TestService.java like so:
You can call this whatever you like, though be sure to edit web.xml appropriately. On the next page, server code.