Developing Web 2.0 Apps with the Google Web Toolkit, Part 2

Ajax development hurts, and is not recommended without a bottle of analgesics by your side. Luckily for us there are tools that can make developing Web 2.0 apps a breeze.

This article is a continuation of the two-part tutorial series on the Google Web Toolkit. In case you missed part one, here’s a quick recap: Part one focused on building client-side user interfaces with GWT by going through the steps to create a sample application and talked about some of the powerful design strategies that can be applied in GWT development to keep code cohesive, maintainable and efficient.

Part one also focused on some of the benefits of using the Google Web Toolkit to build Web 2.0 applications, such as stripped down and optimized client application code, the ability for developers to use their favorite IDEs, and helping developers avoid the headaches of differing DOM implementations across browsers.

The objective of this series is to have the reader come out with a solid understanding of GWT application development, so they can develop their own Web 2.0 client-server applications using GWT with full confidence. Part one covered the client-side of Web 2.0 application development, part two will focus on server-side integration using GWT. This article will go into the details of server communication in GWT applications, as well as elaborate on some of the issues and strategies which can be used to integrate GWT with other popular web application frameworks.

Communicating with a Server

The Google Web Toolkit offers two choices for client-server communication. The first is the GWT RPC mechanism, which uses specialized Java Servlets to process and respond to RPC requests. This is ideal for developers who are building a web application and are planning to use a server that supports Servlet technology.

However, although developers can use GWT RPC services to implement their application server, this doesn’t mean that these will replace any other technology such as J2EE servlets or Spring controllers. GWT RPC services can also be viewed as gateways to other servlets more appropriate for the application architecture, and simply as a way to communicate from your client to your server. We will explore how to use GWT RPC services as an application backend and as a gateway to Spring in a later section.

The second option for server communication is the general purpose RequestBuilder class. As the name suggests, the RequestBuilder class allows you to build custom HTTP requests that you can send to your server for processing. This essentially allows developers to use the backend technology of their choice depending on their application needs.

Using the GWT RequestBuilder to communicate with the server

For example, going back to the FruitMart GWT application, suppose we wanted to implement a PHP backend service that logs the number of fruit purchased per customer to some server record. Let’s name the PHP script storerecord.php and assume that the script reads fruitItemQty and user key value pairs passed in as URL parameters. Suppose we wanted to log a new purchase of 12 fruits for user John Doe. We could make a request to the storerecord.php script providing the parameter values using the RequestBuilder class, as shown in the code snippet below:

private void processPurchaseOrder(String fruitItemQty, String user) {
  StringBuffer urlParams = new StringBuffer();
  urlParams.append("fruitItemQty=" + URL.encodeComponent(fruitItemQty));
  urlParams.append("user=" + URL.encodeComponent(user));
  RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
GWT.getModuleBaseURL() + "storerecord.php?" + urlParams.toString());
  try {
  Request req = builder.sendRequest(null, new RequestCallback() {
    public void onError(Request request, Throwable t) {
      Window.alert("FruitMart couldn't store purchase record.");
  public void onResponseReceived(Request request, Response response) {
    if(response.getStatusCode() == 200) {
      Window.alert("FruitMart stored purchase record successfully.");
    } else if(response.getStatusCode() == 404) {
      Window.alert("FruitMart store record service not available.");
 } catch (RequestException re) {
   GWT.log("Error", re);

Notice the calls to the URL.encodeComponent(String component) method when preparing the URL parameter values and adding them to the URL parameter list. This is a necessary step to make sure that any unsafe values, such as the space character in “John Doe,” are properly escaped in the actual GET request. Similarly, GWT provides a URL.decodeComponent(String component) method which returns the unescaped version of the URL component.

Also note the call to GWT.getModuleBaseURL() when instantiating the RequestBuilder with the request URL constructor argument. The GWT.getModuleBaseURL() method call returns the URL prefix to the GWT module; or more specifically, the location of the md5_hash.nocache.html file. In this example, the assumption was made that the storerecord.php resource lives in the same directory as the GWT module.

When running in hosted mode, this is always true, however it is safe to omit the call to GWT.getModuleBaseURL() and pass in the relative or absolute URL to a deployed resource in a production environment if you intend to locate files in separate paths.

Using the GWT RPC mechanism to implement and communicate with the application server side

The RequestBuilder class essentially permits application developers to have their GWT client-side code interface with any custom server-side components. However, in typical enterprise web application environments, the use of Servlet technology to implement the application backend is often the better choice over implementing a disparate set of server scripts. For this reason, GWT offers the GWT RPC mechanism to conveniently build enterprise grade web applications using custom RemoteServiceServlet subclasses to implement the backend or to act as gateways to integrate into other web application frameworks.

Let’s look at implementing services for our FruitMart web application using the GWT RPC mechanism. It might be worth quickly reviewing the FruitMart web application UI layout and understanding how each of the widgets we defined fit in. Here is the screenshot of the FruitMart web application once more to help remember the layout:

Figure 1: Screenshot of the FruitMart Web application

Let’s review the FruitMart web application UI layout. The panel that the application itself is loaded on is the mainPanel defined in the entry point class onModuleLoad method. On the left hand side of the page is the fruitStandsPanel, which includes an instance of a FruitStandPanel under each tab. Each FruitStandPanel contains multiple FruitItemTypeWidget types for each fruit item type that the fruit stand contains.

On the right hand side is a similar design. We have the fruitBasketPanel defined in the onModuleLoad method which includes a set of FruitBasketItemWidget types. Each FruitBasketItemWidget type contains a set of FruitBasketItemTypeWidget types for each fruit basket item type that the fruit item contains. At the bottom of the fruitBasketPanel is the “Confirm” button, which the user can click to confirm their fruit basket order.

Now that we’re clear on the widgets composing our application interface, let’s continue with the steps to implement an RPC service for our application. Recall that in our FruitMart web application, the ClickListener that was added to the “Confirm” button simply responded to the confirm action by displaying a “thank you” message stating that the order had been placed. Here is that code snippet below:

//Attach order confirmation button to fruit basket.
Button fruitBasketConfirmButton = new Button();
fruitBasketConfirmButton.addClickListener(new ClickListener() {
  public void onClick(Widget sender) {
    Window.alert("Thanks for your order! Your fruit basket will be " +
      "delivered within the next couple hours!");

Now let’s suppose that we have to check in with some inventory system first before confirming that the order has been processed. This would require making a call to the server-side maintaining this inventory system and waiting on the callback to determine whether or not the order has been confirmed. Furthermore, let’s assume that if the order is confirmed, we want to display the order number to the customer. Let’s assume a sentinel value of 0 to represent an unconfirmed order.

Before coding the GWT RPC components implementing this backend functionality, it’s important to understand how the GWT RPC system works. Take a moment to familiarize yourself with the GWT RPC plumbing diagram in Figure 2.

Figure 2: GWT RPC plumbing diagram

Each service has a small family of helper interfaces and classes. Most of these classes are imported framework classes or are automatically generated, and you will generally never need to interact with them other than to have your services extend or serve as an interface to them. The only components you will need to manually code are the ones shown in blue in the plumbing diagram: YourServiceImpl class for the service implementation of the service, YourService interface for the client-side interface to your service , and YourServiceAsync for the asynchronous interface to your service. The pattern for helper classes and handwritten RPC service components displayed in the plumbing diagram is identical for every service that you implement.

Setting up the ProcessOrder RPC service

The best way to gain a better understanding of the GWT RPC mechanism is to start coding RPC components. Let’s begin by creating the service that confirms fruit basket orders in our FruitMart web application. We’ll call this the ProcessOrder service.

First, let’s define the ProcessOrderService service interface. Create the com.google.fruitmart.client.service package where our client-side service interfaces will reside. Next, create the ProcessOrderService interface in that package. Referring to the RPC plumbing diagram, this interface must extend the RemoteService framework interface.

package com.google.fruitmart.client.service; 

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

public interface ProcessOrderService
 extends RemoteService {

Next, let’s define a confirmOrder service method on the ProcessOrderService interface:

public String confirmOrder(int fruitItemQty);

Now let’s define the asynchronous ProcessOrderServiceAsync interface in the com.google.fruitmart.client.service package. The asynchronous version of the ProcessOrderService service interface must be defined in the same package and be named the same as the service interface with an “Async” suffix:

package com.google.fruitmart.client.service; 

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

public interface ProcessOrderServiceAsync { 

  public void confirmOrder(int fruitItemQty, AsyncCallback callback);

You’ll notice that the confirmOrder method signature for the asynchronous interface differs from the service interface implemented earlier by taking an extra AsyncCallback parameter. This is actually necessary by the nature of asynchronous method calls, which require the caller to pass in a callback object which gets notified when the asynchronous call completes. The callback object also gets passed the response message generated from the asynchronous call. For this reason, asynchronous methods do not have return types and always return void.

Next, we define the actual ProcessOrderServiceImpl service implementation. This service will not reside in the same client package containing the translatable client-side code. Recall that the service implementation class is an actual servlet that will be run as Java bytecode. With this in mind, let’s create the com.google.fruitmart.service package and create the ProcessOrderServiceImpl service implementation in that package. For the purposes of this tutorial, let’s assume a simplistic decision making model to determine whether or not we have fruits in stock by selecting a random number and verifying that the fruit item quantity ordered is less than that number.

The ProcessOrderServiceImpl class could be implemented as shown in the code snippet below:

package com.google.fruitmart.service; 

import com.google.fruitmart.client.service.ProcessOrderService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet; 

public class ProcessOrderServiceImpl extends RemoteServiceServlet
  implements ProcessOrderService { 

 public String confirmOrder(int fruitItemQty) {
  int randomNumber = (int)( (2*fruitItemQty) * Math.random()); 

  if(fruitItemQty <= randomNumber) {
    return String.valueOf(Math.round(9999 * Math.random() + 1));
  return "0";

Next, let’s actually make the call to the ProcessOrderService service. We’ll want to process a fruit basket order when the user clicks on the “Confirm” button, so let’s first clear out the old onClick code for the confirm button ClickListener and replace it with the new code calling the ProcessOrderService:

fruitBasketConfirmButton.addClickListener(new ClickListener() {
    public void onClick(Widget sender) { 

     final ProcessOrderServiceAsync processOrderService = (ProcessOrderServiceAsync)
GWT.create(ProcessOrderService.class); /*(1)*/
processOrderService).setServiceEntryPoint(GWT.getModuleBaseURL() +
"/processorder"); /*(2)*/
    processOrderService.confirmOrder(0 /* getFruitItemQuantity()? */, new
AsyncCallback() { /*(3)*/
    public void onFailure(Throwable caught) {
     Window.alert("Sorry, the FruitMart is currently unavailable. Please " +
      " try resubmitting your order later.");
    public void onSuccess(Object result) {
     if(result != null && !((String) result).equals("0")) {
      Window.alert("Thanks for your order! Here is your order#: " + result);
    } else {
      Window.alert("Sorry, we're currently out of stock. Try again later.");

A lot happens in the code snippet above. Let’s take a look at each part individually to gain a better of understanding of what’s involved in making the RPC call to the ProcessOrderServiceImpl service class.

In (1), we see an example of what’s called “Deferred Binding”. Recall that when the GWT compiler reads and compiles your Java application code, it translates it into several permutations of equivalent JavaScript on a per browser basis. This is necessary so that your GWT application can run on any of the major supported browsers, and so that your clients only have to download that bit of JavaScript appropriate to their browser to run your application. The decision of which permutation to bind to your client occurs as the GWT bootstrap script included in your host HTML page is run, hence the term “Deferred Binding.”

At the heart of a GWT RPC call is an XmlHttpRequest (XHR), and the JavaScript code to create the XHR varies from browser to browser. For this reason using the “Deferred Binding” technique is necessary to make a GWT RPC call. In simple terms, the GWT.create call is what tells the GWT compiler that “deferred binding” must occur to select the right permutation to make the GWT RPC call on the ProcessOrderService service interface.

The next part that may seem tricky is casting the GWT.create return type to ProcessOrderServiceAsync, but actually this makes sense. By the very nature of XHR, we must deal with an asynchronous interface on the client-side. GWT RPC plumbing takes care of making the GWT.create return type the asynchronous ProcessOrderServiceAsync service.

In (2), we’re setting the service entry point to the ProcessOrderService. This is basically telling the GWT RPC system which URL it should issue the RPC request to whenever invoking a method on the service. Referring back to the GWT RPC Plumbing diagram above, we can see that it’s safe to cast ProcessOrderServiceAsync as a ServiceDefTarget type. The service entry point we’re setting is GWT.getModuleBaseURL() + "/processorder". GWT.getModuleBaseURL() returns the URL prefix for the GWT application module. In hosted mode, this would resolve to http://localhost:8888/com.google.fruitmart.FruitMart/ since that is where our FruitMart.html and md5_sum.nocache,html files are located in the GWT compiler’s generated output. This path works since we will later be testing the RPC call in hosted mode, and could even work running in deployed web mode if we expect the URL mappings to our RPC servlets to be relative to the path to the *.nocache.html file.

If you wanted to have your RPC servlets mapped to a non-relative URL in your deployed environment, you would simply call setServiceEntryPoint on your service and pass in the absolute path to your service as an argument. In order to have your RPC servlets configured for both the hosted mode and web mode environment without having to constantly toggle the URL paths passed in to setServiceEntryPoint, GWT offers a convenient GWT.isScript() which determines whether or not the running code is JavaScript or byte code.

In (3), we’re making the confirmOrder call on the processOrderService and defining an anonymous inner AsyncCallback class to be notified when the RPC call completes. The onFailure and onSuccess methods are straightforward; what is slightly unclear is the first parameter value that we are interested in passing to the confirmOrder call.

From our specifications, we want to pass in the total number of fruits that have been picked and added to the basket, so it makes sense to define and call some method similar to the getFruitItemQuantity method commented out in the confirmOrder call. However, recall that in our current widget hierarchy, we have a VerticalPanel named fruitBasketPanel which contains FruitBasketItemWidget types which in turn contain FruitBasketItemTypeWidget types, which hold the fruit item quantity information. With this setup, the getFruitItemQuantity might look something like this:

private String getFruitBasketItemQuantity(VerticalPanel fruitBasketPanel) {
  int quantity = 0;
  for (int i = 0; i < fruitBasketPanel.getWidgetCount(); i++) {
    Widget fruitBasketItem = fruitBasketPanel.getWidget(i);
    if(fruitBasketItem instanceof FruitBasketItemWidget) {
      for (int j = 0; j < ((FruitBasketItemWidget)
fruitBasketItem).getVerticalPanel().getWidgetCount(); j++) {
      Widget fruitBasketItemType = ((FruitBasketItemWidget)
      if(fruitBasketItemType instanceof FruitBasketItemTypeWidget) {
       for(int k = 0; k < ((FruitBasketItemTypeWidget)
fruitBasketItemType).getVerticalPanel().getWidgetCount(); k++) {
         Widget fruitBasketItemType = (FruitBasketItemTypeWidget)
         if(fruitBasketItemType instanceof FruitBasketItemTypeWidget) {
           quantity += ((FruitBasketItemTypeWidget)

Using this method would require declaring the fruitBasketPanel as final so that it can be accessed in the anonymous inner AsyncCallback class, as well as defining getVerticalPanel methods on each of the next level widgets so that we can access their inner widgets.

As you can tell, this method of drilling down to the FruitBasketItemTypeWidget types to get the fruit item quantity information is inelegant and cumbersome. We will have to make a small redesign to how our fruitBasketPanel and nested widgets are arranged to make it easier to get fruit item quantity information.

Visualizing and composing widgets as visual and logical containers

It may seem like we’re revisiting client-side UI code, but there is actually an important difference. Where part one of this article focused on client-side UI layout and design, this particular redesign has to do with accessing client-side information and getting it across to the server-side.

There is an important distinction to be made here, namely, using widgets as visual UI containers versus logical containers. In the code snippet above, we are trying to extract the fruit item quantity information by digging into the widgets as visual containers. In essence, we’re digging to the next inner widget, extracting its UI component (e.g. VerticalPanel), and then digging into its widgets to eventually get the FruitBasketItemTypeWidget types out.

Instead, we should modify these widgets in such a way that they logically maintain their own lists of the types they contain so it becomes intuitive to access those types and extract any information we need.

This means that, rather than have a fruitBasketPanel declared as a VerticalPanel in the onModuleLoad method in the entry point class, we would create a FruitBasketPanel composite that maintains a logical list of the widgets it contains and declare the fruitBasketPanel as this composite instead.

We then also modify FruitBasketItemWidget to have it maintain a logical list of the widgets it contains, as well as modify the FruitBasketItemTypeWidget class so that it returns the quantity picked via a getFruitBasketItemTypeQuantity method. During this redesign we can see the power of using a Java IDE for refactoring code for just these kinds of situations. For example, using Eclipse, making these changes is literally a few clicks and keystrokes away.

However, by virtue of the Java programming language itself, making these changes using a simple text editor should be a quick task. First, create the FruitBasketPanel class extending Composite in the com.google.fruitmart.client package. Then, take all the declarations of the fruitBasketPanel and all its nested widgets out of the onModuleLoad method and declare them as member variables in FruitBasketPanel. Also, declare a List member variable called fruitBasketItems that will serve as a logical reference to the FruitBasketItemWidget types contained in the FruitBasketPanel.

Next, strip out the calls setting the UI layout and adding the label and button widgets to the fruitBasketPanel and place them in the FruitBasketPanel constructor. Finally, define public addFruitBasketItem(FruitBasketItemWidget fruitBasketItem and removeFruitBasketItem(FruitBasketItemWidget fruitBasketItem) which will serve to logically add and remove FruitBasketItemWidget types from the fruitBasketItems list. After making these changes, your FruitBasketPanel class should look similar to this code listing:

package com.google.fruitmart.client;

import com.google.fruitmart.client.service.ProcessOrderService;
import com.google.fruitmart.client.service.ProcessOrderServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget; 

import java.util.ArrayList;
import java.util.List; 

public class FruitBasketPanel extends Composite { 

   private VerticalPanel fruitBasketPanel = new VerticalPanel();
   private Label fruitBasketLabel = new Label("Fruit Basket");
   private Button confirmButton = new Button();
   private List fruitBasketItems = new ArrayList(); 

   public FruitBasketPanel() {
    confirmButton.addClickListener(new ClickListener() {
     public void onClick(Widget sender) {
      final ProcessOrderServiceAsync processOrderService = \
	processOrderService).setServiceEntryPoint(GWT.getModuleBaseURL() \
	+ "/processorder");
	new AsyncCallback() {
	public void onFailure(Throwable caught) {
	  Window.alert("Sorry, the FruitMart is currently unavailable. \
		Please " +
           " try resubmitting your order later.");
	public void onSuccess(Object result) {
	 if(!((String) result).equals("0")) {
	  Window.alert("Thanks for your order! Here is your order#: \
	 " + result);
	} else {
	  Window.alert("Sorry, we're currently out of stock.
	Try again later.");


public void addFruitBasketItem(FruitBasketItemWidget \
	fruitBasketItem) {

//insert the next fruit basket item such that it is positioned just before the confirm button
	fruitBasketPanel.setCellWidth(fruitBasketItem, "100%");

  public void removeFruitBasketItem(FruitBasketItemWidget \
	fruitBasketItem) {

We’ll also need to change a few things in the FruitMart entry point class to reflect usage of the new FruitBasketPanel composite widget. First, change the declaration of the fruitBasketPanel variable in the onModuleLoad method from a VerticalPanel to a FruitBasketPanel: FruitBasketPanel fruitBasketPanel = new FruitBasketPanel(); Next, change the attachFruitBasketItems method to take a FruitBasketPanel as a parameter instead of a VerticalPanel, and at the end of the method, change the fruitBasketPanel.add calls to fruitBasketPanel.addFruitBasketItem:

private void attachFruitBasketItems(FruitBasketPanel fruitBasketPanel) { 


Finally, to be consistent with our new logical view of our composites and their nested widgets, let’s apply the same changes to FruitBasketItemWidget by adding a List called fruitBasketItemTypes and addFruitBasketItemType, removeFruitBasketItemType and getFruitBasketItemTypes methods. The code snippets here display the changes we need to make:

import java.util.List;
import java.util.ArrayList;

 public class FruitBasketItemWidget extends Composite {
   private List fruitBasketItemTypes = new ArrayList();

public void addFruitBasketItemType(FruitBasketItemTypeWidget \
	fruitBasketItemType) {
   fruitBasketItemPanel.setCellWidth(fruitBasketItemType, "100%");

 public void removeFruitBasketItemType(FruitBasketItemTypeWidget \

  public List getFruitBasketItemTypes() {
  return fruitBasketItemTypes;

Having now implemented and used our composite widgets as both visualization and logical containers, we can now implement the getFruitBasketItemTypeQuantity method in the FruitBasketPanel class in a straightforward manner:

import java.util.Iterator;

public class FruitBasketPanel extends Composite {

   private int getFruitItemQuantity() {
     int quantity = 0;
     for (Iterator iter = fruitBasketItems.iterator(); iter.hasNext();) {
     FruitBasketItemWidget fruitBasketItem = (FruitBasketItemWidget) \
     for (Iterator iterator = \
iterator.hasNext();) {
	FruitBasketItemTypeWidget fruitBasketItemType = \
	quantity += fruitBasketItemType.getFruitBasketItemTypeQuantity();
     return quantity;

And finally, we must add the getFruitBasketItemTypeQuantity method to the FruitBasketItemType class so it can return the quantity picked:

public int getFruitBasketItemTypeQuantity() {
  try {
    return Integer.valueOf(fruitBasketItemTypeQuantity.getText()).intValue();
  } catch(NumberFormatException nfe) {
    return 0;

Configuring the ProcessOrderServiceImpl servlet in hosted mode

Now we need to configure the ProcessOrderServiceImpl class on our servlet container. There’s nothing special here in that you would configure the ProcessOrderServiceImpl servlet just like any other servlet by making an entry and defining a URL mapping in the web.xml deployment descriptor for the web application.

However, if you just want to start performing end-to-end debugging without going through the hassle of first setting up a custom server, GWT offers a very convenient way to get you on the fast track to the code-test-debug cycle. GWT’s hosted mode allows you to configure your RPC servlets on the embedded Tomcat server. This means that we can run and debug our FruitMart application end-to-end using the GWT hosted mode browser.

Configuring the servlets on the embedded Tomcat server is just a matter of adding the appropriate entries to the GWT application’s module XML file; in our case, FruitMart.gwt.xml. Let’s add a new entry to the FruitMart.gwt.xml to configure our new ProcessOrderServiceImpl servlet. Open FruitMart.gwt.xml and add the following entry:

<servlet path="/processorder"
class="com.google.fruitmart.service.ProcessOrderServiceImpl" />

And that’s it! The RPC servlet is now configured for hosted mode. The "/processorder" is a relative URL path; specifically, it is relative to the GWT module path. Recall that when we instantiated the RPC service and set its service entry point, we set the URL path to GWT.getModuleBaseURL() + "/processorder", where GWT.getModuleBaseURL returns the GWT module path.

Let’s try running our newly server integrated FruitMart Web application and see if we can successfully confirm a fruit basket order. Recall that we originally created a FruitMart-shell hosted mode script when we created the FruitMart application using the applicationCreator. Run that script now to view the FruitMart application in hosted mode, and try to make some fruit basket orders to see if you get a server response. Also, keep in mind that you can now debug the FruitMart application in hosted on both the client-side and the server-side by running the script using your favorite Java debugging tool.

Integrating GWT with other web application frameworks

As mentioned earlier, one of GWT’s goals is to make Web 2.0 enterprise web application development easier by bringing Ajax development to a mature, time-tested and strongly typed language like Java to allow for cohesive design and a maintainable code base. In keeping with this goal, GWT is also designed in such a way that it can easily integrate with the many mature and time-tested web application frameworks developed to make web application development easier.

We will take a look at techniques we can use to integrate GWT with two popular web applications frameworks: Struts and Spring. This article assumes that the reader is already somewhat familiar with these technologies.

Integrating GWT with Struts

First let’s take a look at integrating GWT with the Struts framework. The Struts framework has proven to be very useful for large-scale web application development because of how the framework naturally lends itself to the Model-View-Controller (MVC) architecture. The framework defines components which each play one of the roles in the MVC trio. As long as the developer using the framework follows the Struts implementation of the MVC framework, they are guaranteed to have cleanly separated code where changes in one component have little or no effect on the other. (For more details on the Struts framework, check out the .)

The role of the Controller is played by the Struts Action Servlet. The Action Servlet intercepts URL paths in incoming requests and passes the request data to appropriate user-defined Action classes that know how to handle the request. The mappings between URL paths and handling Action classes are defined in a Struts configuration file. The role of the View is played by JSP pages, which are responsible for rendering the application view for the user, and can be extended through the use of custom tags. The role of the Model is typically played by a set of Java business and value objects. These are responsible for implementing the application business logic and interfacing with backend systems for application data storage and retrieval.

Given this implementation of the MVC architecture, it becomes difficult to integrate GWT with the Struts framework. Because Web 2.0 application development transforms the client-server architecture from a stateless client-stateful server infrastructure to a stateful client-stateless server infrastructure, implementations of the MVC architecture such as the one prescribed for the Struts framework are hard to integrate into the Web 2.0 platform. However, it is possible to implement an MVC architecture in GWT code, but the components that play each role in the MVC trio differ wildly from those in the Struts framework. In GWT, the Model and the View are both captured by the composite widgets we defined. In fact, as we have seen earlier, composite widgets are both logical containers as well as visual containers. This almost directly translates into the composite widgets being both the Model and the View in the MVC architecture. The Controller components would be the EventListeners, which determine which actions to perform based on the user’s inputs to the system.

After having explained this, it’s clear that the Struts MVC implementation and the aforementioned GWT MVC implementation don’t mesh very well, and it would be difficult and nonsensical to find a midway solution so that they would mesh. However, although integrating GWT and Struts infrastructures could prove to be an arduous task, integrating GWT modules into a web application based on the Struts framework is very simple.

This is possible due to the general purpose RootPanel.get("some_id").add() method call. Looking back to our FruitMart web application, we added the mainPanel to the RootPanel by calling RootPanel.get().add(mainPanel) in the entry point class’ onModuleLoad method without passing an argument to RootPanel.get(). This added the mainPanel to the “body” of the page, in essence making the GWT application become the page itself.

When we call RootPanel.get("some_id").add(mainPanel) with “some_id” as a parameter, we’re telling the GWT bootstrap procedure to look for an element with “some_id” in the page, and bind the GWT application to that element. What this means is that by defining an element with “some_id” in some arbitrary web page and including the GWT application bootstrap file, the GWT application will load up as a component on the page in the designated element.

As a more concrete example, let’s suppose our FruitMart web application has done very well for us in the market place and we have decided to buy out the much larger online food store, BuzzMart. Let’s further assume that BuzzMart ran a successful online business running a web application based on the Struts framework, and we are now interested in integrating the FruitMart into the BuzzMart application. Let’s suppose the main application page where we want to display the FruitMart is in some corner of the main BuzzMart.jsp page. All we would need to do to include the FruitMart application is first define an appropriate div in the JSP page, like so:

<div id="FruitMart" />

Next, we would modify the FruitMart entry point class onModuleLoad method to add the mainPanel to the element with id “FruitMart”:


And finally, we would include the <script> tag referencing the FruitMart application bootstrap file at the bottom of the <body> in the host JSP page:

<script src="com.google.fruitmart.FruitMart.nocache.js"></script>

And that’s it! The FruitMart application would now run as a component in the BuzzMart.jsp page. This technique makes GWT applications able to load in any page, and thus makes GWT application integration into other applications an easy process. Although it’s great that mixing one GWT application into any another application is quick and simple to do, it isn’t really an example of integrating GWT into another web application framework since the Struts framework MVC doesn’t easily transpose to the Web 2.0 platform.

However, this isn’t the case with the Spring web application framework, which offers a way for us to have our GWT components integrated with Spring technology just by making a few minor tweaks to our GWT RPC service components. Let’s look at the details to accomplish this in the next section below.

Integrating GWT with Spring MVC

The Spring framework was one of the first to introduce the concept of “Dependency Injection,” also known as “Inversion of Control,” and has become a very popular framework of choice for offering a highly configuration-oriented application development style. We will use this technique as part of our integration process. We will also use the Spring DispatcherServlet which will properly select and inject our RPC servlet as the controller for the FruitMart web application.

This integration technique and its explanations are largely inspired by a community contributed Wiki article about integrating GWT with Spring technology hosted on the Google Web Toolkit Incubator project page, which can be found here.

The first step to making this happen is to configure the web.xml file to redirect requests for particular URLs to the DispatcherServlet. Let’s suppose that in our case we want any request made to a URL ending in “.fm” to be redirected to the DispatcherServlet. We could configure this setup in the application web.xml by making the following entries:


Note that in order for requests to be properly redirected to the FruitMartDispatcher, we will need to update the service entry points in our ProcessOrder service call to end with a “.fm”. For example, we could change the setServiceEntryPoint(GWT.getModuleBaseURL() + "/processorder") call to setServiceEntryPoint(GWT.getModuleBaseURL() + "/processorder.fm"). Next, we need to configure applicationContext.xml to tell the FruitMartDispatcher which org.springframework.web.portlet.mvc.Controller to choose to process the request. We can use the org.springframework.web.servlet.handler.SimpleUrlHandlerMapping type to define appropriate mappings:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">d

Before creating the <bean> entries for the processOrderController in the applicationContext.xml file, we must first create the FruitMartController. This controller class can be viewed as the gateway between GWT RPC servlet technology and the Spring MVC controller. Everything prior to this step is standard Spring configuration detail — here is where we are actually writing the component that glues GWT and Spring MVC together.

The processOrderController, and any other controller we care to define, will be defined as the FruitMartController type in its corresponding <bean> entry in the applicationContext.xml file. Each of these controllers will wrap their corresponding RemoteService interface types which will be injected through the <bean> entry property values. What the FruitMartController will essentially do is extend the GWT RemoteServiceServlet and implement the Spring MVC Controller interface, and within each of the implemented interface methods make the corresponding GWT RemoteServiceServlet method call.

Creating the FruitMartController requires a bit more knowledge about the GWT RPC subsystem, so I will skip the details for the sake of brevity in this tutorial series and simply show what the controller would look like in the code listing below. However, if you would like to know more about creating the steps to creating an intermediary controller to glue Spring MVC controllers and GWT RPC servlets together, you can read up on further details in the “IntegratingWithSpring” Wiki document mentioned earlier. The code below is the same as the one used for the GWTController mentioned in the Wiki document, with only a couple of changes to take care of the class name and packaging.

package com.google.fruitmart.controller; 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.SerializationException;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView; 

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

public class FruitMartController
extends RemoteServiceServlet
implements Controller
  // Instance fields
  private RemoteService remoteService;
  private Class remoteServiceClass; 

  // Public methods
  * Implements Spring Controller interface method.
  * Call GWT's RemoteService doPost() method and return null.
  * @param request current HTTP request
  * @param response current HTTP response
  * @return a ModelAndView to render, or null if handled directly
  * @throws Exception in case of errors
  public ModelAndView handleRequest(HttpServletRequest request,
 	 HttpServletResponse response)
	 throws Exception
    doPost(request, response);
    return null; // response handled by GWT RPC over XmlHttpRequest

* Process the RPC request encoded into the payload string and return a string
* that encodes either the method return or an exception thrown by it.

public String processCall(String payload) throws SerializationException
  RPCRequest rpcRequest =
   RPC.decodeRequest(payload, this.remoteServiceClass); 

   // delegate work to the spring injected service
   return RPC.invokeAndEncodeResponse(this.remoteService,
	rpcRequest.getParameters() );

 catch (IncompatibleRemoteServiceException e)
   return RPC.encodeResponseForFailure(null, e);

* Setter for Spring injection of the GWT RemoteService object.
* @param RemoteService the GWT RemoteService implementation
* that will be delegated to by
* the {@code GWTController}.

public void setRemoteService( RemoteService remoteService )
  this.remoteService = remoteService;
  this.remoteServiceClass = this.remoteService.getClass();

Finally, the last bit to complete the integration of GWT with Spring MVC is to define the processOrderController bean in the applicationContext.xml file. This entry should look like this:

<bean name="processOrderController"
<property name="remoteService">
<bean class="com.google.fruitmart.service.ProcessOrderServiceImpl"/>

After going through this integration exercise, you may have noticed that a lot of what we did seems like boilerplate code, and there’s probably a way to wrap that up in a library to make building GWT applications with Spring even easier. If you’d have guessed that a library already exists for just this purpose, you’d have guessed right. The GWT-ServerLibrary (GWT-SL) is a project that aims at leveraging the benefits of the Spring framework for GWT application development. If you’re interested in finding out more about GWT-SL, check it out on the project page here

Concluding the GWT Tour

This tutorial series was a long and, I hope, fun adventure. The goal of this tutorial series was to give the reader a comprehensive overview of GWT technology and how to develop web applications using it, as well as to instill confidence in those who are now ready to go out and start building Web 2.0 applications. If you have followed these steps, you are well on your way to becoming a lean, mean GWT coding machine!

However, there is always more in store for those who want to take their GWT application development skills to the next level. For example, we still haven’t talked about the strong support GWT offers for internationalization, or the support for the GWT JUnit testing framework which enables developers to run JUnit test cases against their GWT client-side code. We also didn’t talk about using the JSON libraries or the very powerful feature called the JavaScript Native Interface, which makes it easier for developers to build GWT mashups and integrate JavaScript code into their GWT code when they need lower level access, and neither did we mention the client-side XML parsing facilities that can make UI customizations or application configurations a breeze to implement.

There are many resources out there to help you learn more about these features, as well as to help you get answers to any inquiries that may come up during your next GWT project. Start with the GWT home page to get started.

Comments on "Developing Web 2.0 Apps with the Google Web Toolkit, Part 2"


Your link to “part one” really just links to this page.


Whoops. Fixed.

Hi my family member! I wish to say that this post is awesome, nice written and come with approximately all vital infos. I’d like to look more posts like this .

Have you ever considered about including a little bit more than just your articles?
I mean, what you say is important and all. Nevertheless just
imagine if you added some great pictures or video clips to give your posts more,
“pop”! Your content is excellent but with pics and clips, this website could
undeniably be one of the very best in its niche. Good blog!

I think this article is very helpful for us,it has solved our problem,thanks!
Wholesale 2140Oakley Sunglasses ID8210095 http://www.fleetsale.ru/new-arrival-oakleys-098.html

What’s up, always i used to check web site
posts here early in the break of day, for the reason that i love
to learn more and more.

Also visit my weblog :: WallyYDais

Wonderful story, reckoned we could combine several unrelated information, nonetheless actually really worth taking a appear, whoa did one discover about Mid East has got more problerms also.

You can definitely watch your enthusiasm within the article you write.
The arena hopes for more passionate writers such as you who are certainly not afraid to
mention the direction they believe. Always follow your heart.

My webpage – EliaXHolling

Leave a Reply