You are on page 1of 23

code::XtremeApps::

Google Web Toolkit Training

Google Web Toolkit (GWT) – a Beginner’s Introduction


(Using GWT to build a simple Snake and Ladder game)

Overview
The purpose of this training is to provide an introduction to some of the fundamental concepts of
Google Web Toolkit (GWT). By going through the steps in developing a simple Snake and
Ladder game, the trainee will learn the following:
• How to install GWT
• How to use GWT’s command-line tools
• Understand GWT’s project structure
• Working with GWT’s widgets and panels
• Communication with server using simple RPC (with RequestBuilder)
• Running GWT application in Hosted and Web mode

Prerequisites
Some programming experience with the Java language and Swing/AWT
Some usage experience with the Eclipse IDE will be great

Final Objective - The Snake and Ladder Game

Page 1 / 23
code::XtremeApps::
Google Web Toolkit Training

Step 1.1 – Setting up the Development Environment


In this training, we will be using the following tools and software:

1.) Sun Java Standard Edition SDK (JDK 5.0 Update 12)
Download Link: http://java.sun.com/javase/downloads/index_jdk5.jsp
Installation Instructions: http://java.sun.com/j2se/1.5.0/install.html

2.) Google Web Toolkit Version 1.4 (Build 1.4.60 - released on August 28, 2007)
Download Link: http://code.google.com/webtoolkit/versions.html
Installation Instructions: http://code.google.com/webtoolkit/gettingstarted.html

3.) Eclipse IDE for Java EE Developers


Download Link: http://www.eclipse.org/downloads/
Installation Instructions: http://www.eclipse.org/downloads/moreinfo/jee.php
(Refer to "Tutorials and Help")

Please note that using a Java IDE like Eclipse is not a must for GWT development, but using
one will definitely make your development effort a more enjoyable and fruitful experience. As
GWT ships with a command line utility that can automatically generate Eclipse project files,
naturally, we will use Eclipse as our development environment. Note that all the sample project
codes distributed with the training materials are also Eclipse-based.

You should be able to follow the installation instructions given in the above URL links for the
installation of the tools and software without any difficulty. But since this is training on GWT, I
will mention briefly about the installation of GWT (which are also available online from GWT’s
Getting Started Guide):

1.1. Download & Install - GWT


1.1.1. Download GWT package for your operating system (Windows, Mac or Linux) from the
above download link.
1.1.2. On Windows, extract the files from gwt-windows-1.4.60.zip with a program like WinZip.
On Mac and Linux, you can unpack the package with a command like:

tar xvzf gwt-mac-1.4.60.tar.gz

1.1.3. GWT does not have an installer application. All the files you need to run and use GWT
are located in the extracted directory. The diagram below shows the list of folders and
files located in the extracted directory (for Windows):

Page 2 / 23
code::XtremeApps::
Google Web Toolkit Training

1.1.4. Take note of the two executable files in the extracted directory: applicationCreator
and projectCreator, which we will be using very soon to create our first GWT
application.

Step 1.2 – Creating our first GWT application


GWT ships with a command line utility called applicationCreator that automatically generates
all the files you will need in order to start a GWT project. As mentioned earlier, GWT can also
generate Eclipse project files and launch config files. This is done by using the command line
utility called projectCreator. In our case, we will be using both command line utilities to create
the skeleton of a GWT application. We will work on this GWT application skeleton to build our
Snake and Ladder game.

1.2. Create a GWT application


1.2.1. To generate an Eclipse project for a new application, use the projectCreator script (fro
the command prompt) to generate a shell Eclipse project for our application. Note that
the –out flag specify the output directory while the –eclipse flag specify the project
name for the Eclipse project.

projectCreator –out SnakeAndLadderDir -eclipse SnakeAndLadderPrj

1.2.2. Then generate our GWT application using the applicationCreator script, noting that
we use an additional -eclipse flag specifying the name of our Eclipse project (as
specified in the previous step). In our case, the name of the entry-point Java class to
be created is “org.itsc.client.SnakeAndLadder”. Note that this tool enforces the best
practice of using “client” as the final package for our entry-point class.

applicationCreator –out SnakeAndLadderDir -eclipse SnakeAndLadderPrj


org.itsc.client.SnakeAndLadder

Page 3 / 23
code::XtremeApps::
Google Web Toolkit Training

1.2.3. The diagram below shows the eventual GWT application directory structure generated
as a results of the above two steps.

Step 1.3 – Understanding the GWT Project Structure


Before we proceed to run the GWT skeleton application generated from the above steps, we
will first explore the GWT project structure and also understand the purpose of some of the files
generated.

1.3. GWT Project Structure


1.3.1. As mentioned in the Getting Started Guide: GWT projects are overlaid onto Java
packages such that most of the configuration can be inferred from the classpath and
your module definitions. If you are starting a GWT project from scratch, you should use
the standard GWT package layout, which makes it easy to differentiate client-side code
from server-side code. For example, suppose your new project is called "Calendar".
The standard package layout would look like this:

Page 4 / 23
code::XtremeApps::
Google Web Toolkit Training

1.3.2. With respect to our GWT skeleton application generated (SnakeAndLadder), let’s take
a look at the purpose of some of the generated files:

SnakeAndLadder.gwt.xml - This is the configuration file for the module that is used to
define the entry-point class, dependencies and compiler directives. The entry-point
class is the class that is executed when the browser loads the module.

SnakeAndLadder.html - This is the HTML file that will load and execute our
SnakeAndLadder application.

SnakeAndLadder.java - This is the sample entry-point class where we will place our
Java codes and these Java codes will be compiled into JavaScript.

SnakeAndLadder-shell.cmd – This is a shell script that executes the hosted-browser


that ships with GWT. The hosted-browser works like a usual web browser but runs
within the GWT development environment. We can execute this shell script to launch
our application in hosted-mode. Note that in hosted-mode, the Java codes are not
compiled into JavaScript yet.

SnakeAndLadder-compile.cmd – This is another shell script that executes the Java


to JavaScript compiler. The JavaScript generated will be placed in a directory called
www.

1.3.3. Now let us try launching our application by running the SnakeAndLadder-shell.cmd
shell script. Alternatively, we can run the SnakeAndLadder-compile.cmd shell script
and then open the file SnakeAndLadder.html (generated into www directory) in our
browser.

Page 5 / 23
code::XtremeApps::
Google Web Toolkit Training

1.3.4. Try clicking on the “Click me” button which toggles the visibility of the “Hello World!”
message

Step 1.4 – Understanding our first GWT application


Next, we will briefly explain the inner workings of our first GWT application by looking into the
content of the generated files. However, let’s do it from within Eclipse environment.

1.4. Understanding our first GWT application (within Eclipse environment)


1.4.1. To open your project in Eclipse, launch Eclipse and click the File -> Import menu.
Choose "Existing Projects into Workspace" in the first screen of the wizard, and enter
the directory in which you generated the .project file in the next screen of the wizard.
When you are complete, you should see your GWT project loaded into your Eclipse
workspace:

Page 6 / 23
code::XtremeApps::
Google Web Toolkit Training

Note: the”-01” appended to the project name is


a number to mark the stages of development of
our SnakeAndLadder game.

For easier reference and understanding, the


source codes for all development stages are
provided for you.

1.4.2. Looking into the content of SnakeAndLadder.gwt.xml. Recall that:

SnakeAndLadder.gwt.xml - This is the configuration file for the module that is used to
define the entry-point class, dependencies and compiler directives. The entry-point
class is the class that is executed when the browser loads the module.

Page 7 / 23
code::XtremeApps::
Google Web Toolkit Training

1.4.3. Looking into the content of SnakeAndLadder.html. Recall that:

SnakeAndLadder.html - This is the HTML file that will load and execute our
SnakeAndLadder application.

Page 8 / 23
code::XtremeApps::
Google Web Toolkit Training

1.4.4. Looking into the content of SnakeAndLadder.java. Recall that:

SnakeAndLadder.java - This is the sample entry-point class where we will place our
Java codes and these Java codes will be compiled into JavaScript.

Adding a Button widget with


“Click me” as the button text.

Adding a ClickListerner to
the “Click me” button, so that
the button can respond to a
mouse click event on it.

Adding the “Click me” button


onto the browser page
(through the RootPanel).

Step 1.5 – Working with GWT Widgets and Panels


Next, we will start working on our SnakeAndLadder game, using the GWT skeleton application
as our base. We will start by designing the graphical user interface (GUI) of our game with
GWT widgets and panels. As mentioned in the GWT Developer Guide:

GWT applications construct user interfaces using widgets that are contained within panels.
Widgets and panels work the same way on all browsers; by using them, you eliminate the need
to write specialized code for each browser. Examples of widgets include Button, TextBox, and
Tree. But you are not limited to the set of widgets provided by the toolkit. There are a number
of ways to create custom widgets yourself. Panels, such as DockPanel, HorizontalPanel, and
RootPanel, contain widgets and are used to define how they are laid out in the browser.

Page 9 / 23
code::XtremeApps::
Google Web Toolkit Training

Page 10 / 23
code::XtremeApps::
Google Web Toolkit Training

1.5. Working with GWT Widgets and Panels


1.5.1. The main GUI for our Snake And Ladder game is designed with the use of the following
panels:
• HorizontalPanel
• AbsolutePanel
• VerticalPanel
• Grid
And the following widgets:
• Image
• Button
• TextArea
We will also be using DialogBox, PopupPanel and DockPanel at a later stage of the
development.

HorizontalPanel (red) and AbsolutePanel (blue)

VerticalPanel (red) and Grid (blue)

Page 11 / 23
code::XtremeApps::
Google Web Toolkit Training

1.5.2. The java source file SnakeAndLadder.java is updated to reflect our main GUI design.
The listing below shows where some of the codes updates are done. For the complete
program source code up till this stage, please refer to the Eclipse project:
SnakeAndLadderPrj-02.

The JPEG file containing


the Snake and Ladder game
board image.

Using a predefined style


name to set the visual style
of the TextArea.

(Refer to a later step on


describing how to use CSS
in GWT applications)

Do note that we have not added any listener to the widgets yet, which means the widgets e.g.
buttons, will not react to any UI events e.g. button click.

Page 12 / 23
code::XtremeApps::
Google Web Toolkit Training

1.5.3. Notice that we have placed the image file boardImage.jpg showing the Snake And
Ladder game board into the “src/org.itsc/public/img” directory. This file is used in the
creation of the Image widget.

1.5.4. We can make use of Cascading Style Sheets (CSS) defined in the application’s CSS
file to define the widgets’ associated visual styles. In our case, the
SnakeAndLadder.css CSS file is created in the “src/org.itsc/public” directory with the
following content.

1.5.5. In addition to creating the application CSS file, we will also need to update the module
file SnakeAndLadder.gwt.xml so that GWT is kept informed about this dependency.

Page 13 / 23
code::XtremeApps::
Google Web Toolkit Training

Step 1.6 – Adding Listener (to widgets) and Game Logic


Next, we will allow our widgets to respond to UI events by adding appropriate Listener objects to
the widgets. We will also introduce some simple game logic into our code e.g. adding game
players, emulating dice roll, players movement on game board, encounters with Snake and
Ladders etc.

Note that this will be longest section of the entire training guide as we will also be introducing
two additional Java classes to our project to support the game logic, namely: Player.java and
SnakeAndLadderMap.java. We will give brief explanations of the purpose of these two
classes but will not go into the details (as these are more game logic codes and not really
GWT-dependent). For the complete program source code up till this stage, please refer to the
Eclipse project: SnakeAndLadderPrj-03.

1.6. Adding Listener (to widgets) and Game Logic


1.6.1. Firstly, let’s take a look at a ClickListener object is added to the “New Game” button to
handle the event where the button is clicked.

Key steps:
• We called the addClickListener() method to add a ClickListener to the button.
• For code simplicity, the ClickListener object is created as an anonymous class within
the method call itself (the codes highlighted in blue).
• We implemented the onClick() method and added codes to handle the event where the
button was clicked.
• The codes within onClick() are game logic codes dealing with mostly initializations stuff
e.g. players’ turn, players’ position on game board etc.
• One thing to note is that as boardPanel is an instance of AbsolutePanel, we can set the
players icons (Image widget) position at any location on the boardPanel by using the
setWidgetPosition() method and passing the XY coordinates as part of the parameters
list.
• We can set the content of a TextArea by using the setText() method.

Page 14 / 23
code::XtremeApps::
Google Web Toolkit Training

1.6.2. Similarly, we have added a ClickListener to the “Roll Dice” button but the codes within
the onClick() method is more complicated due to the numbers of tasks that need to be
performed when this button is clicked. The following steps look at a few code segments
within this method.

1.6.3. GWT’s Random and Timer class used to emulate dice roll animation.

Key points:
• Note that GWT Random and Timer class are defined in com.google.gwt.user.client
package.
• Note that we cannot use the Random class defined in the usual java.util package as
this class is not part of GWT’s JRE Emulation Library.
• For the full list of classes and methods that are available in GWT’s JRE Emulation
Library, you can refer to: http://code.google.com/webtoolkit/documentation/jre.html.
• Remember that GWT’s client-side code will eventually be compiled into its equivalent in
JavaScript.
• Notice also the use of CSS to set the visual styles for the dice buttons.
• The Timer class is a simplified, browser-safe timer class. This class serves the same
purpose as java.util.Timer, but is simplified because of the single-threaded
environment.

1.6.4. Creating and popping up a DialogBox whenever a Snake or Ladder is encountered by


the players. Besides showing how a DialogBox can be constructed, this code segment
also illustrates the use of a DockPanel for layout of widgets and a HTML widget to
display HTML-styled text on the panel.

Page 15 / 23
code::XtremeApps::
Google Web Toolkit Training

Creating of DialogBox during Snake or Ladder encounters

Page 16 / 23
code::XtremeApps::
Google Web Toolkit Training

1.6.5. The Player class file is design to be a template for creating player objects. The class
members included are: an Image widget to represent the player icon appearing on the
game board and the player positional information.

In addition, the following piece of code segment within the Player class will create a
PopupPanel whenever there’s a MouseOver event for the player’s Image widget. It will
also capture MouseMove events to move the PopupPanel with the mouse.

Creating of PopUpPanel onMouseOver

1.6.6. Finally, the SnakeAndLadderMap class file basically allows the application to know the
locations of all snakes and ladders.

A HashMap from the java.util package is used to store the starting and ending points of
the snakes and ladders. Note that we can use the HashMap class direct from the usual
package as this class is part of GWT’s JRE Emulation Library.

Page 17 / 23
code::XtremeApps::
Google Web Toolkit Training

Step 1.7 – Communication with Server using RequestBuilder


So far, all the codes that we have developed are client-side code, i.e. the codes will be
compiled by GWT compiler into JavaScript and run from the client browser. It is important to
remember that for client-side code, we can use only libraries and Java language constructs that
can be translated by the GWT compiler.

When a web application needs to interact with a backend server (for e.g. to load or save data),
it will need to make a client-side request (from the browser) to the server. The mechanism for
interacting with a server across a network is called making a remote procedure call (RPC).
While processing a RPC, the server is executing server-side code. As mentioned in GWT
Reference Guide: GWT does not meddle with your ability to run Java bytecode on your server
whatsoever. Server-side code doesn't need to be translatable, so you're free to use any Java
library you find useful.

In the context of AJAX-based web applications, modern browsers include a special JavaScript
object called the XMLHttpRequest object that allows asynchronous communication between
the browser and the server. This asynchronous mode of communication allows e.g. updating a
portion of a web page without forcing a page refresh like traditional HTTP request/response
communication model.

GWT provides two mechanisms for RPC that sit on top of the XMLHttpRequest object. The first
mechanism is based on the RequestBuilder class, which is essentially a wrapper around the
XMLHttpRequest object. The second mechanism is GWT-RPC, which is a more
comprehensive mechanism that gives you much more flexibility.

Page 18 / 23
code::XtremeApps::
Google Web Toolkit Training

For example, RequestBuilder allows only exchange of text between the client and server. If
support of complex data structure is required, custom serialization and deserialization codes
must be written. GWT-RPC, on the other hand, allows you to send any serializable Java
objects (with support for automatic serialization and deserialization).

In our case, as implementing GWT-RPC is beyond the scope of this training targeted at
beginners, we will implement a simple scenario of client-server communication using the
RequestBuilder class.

1.7. Simple RPC with RequestBuilder


1.7.1. We first create a servlet, WordsOfWisdomServlet that will return a random text-based
word of wisdom to the requester. Note that we should not place this servlet class in the
org.itsc.client package as this is a piece of server-side code and we do not want it to be
compiled into JavaScript. Instead, we place this servlet class into the org.itsc.server
package.

1.7.2. Next, we add a ClickListener object for the “WoW” (Words of Wisdom) button and
within its onClick() method, we add the code to create a RequestBuilder object pointing
to our WordsOfWisdomServlet.

Page 19 / 23
code::XtremeApps::
Google Web Toolkit Training

1.7.3. Note that the last parameter to the RequestBuilder constructor is the string
“wordsofwisdom”. This is actually the servlet name that will be mapped to the
org.itsc.server.WordsOfWisdomServlet which we have created earlier. This mapping
information need to be manually defined in the module file SnakeAndLadder.gwt.xml.

In addition, as our WordsOfWisdomServlet is using the com.google.gwt.http package


to use the RequestBuilder class, we need to state this dependency in the module fiel as
well.

1.7.4. Since this will be an asynchronous communication, the requester will not wait for a
response from the server before continuing with its execution. Thus, when the
requester sends out its request, it will need to assign a callback handler (a Java object)
which will be responsible in handling the response when it arrives. In GWT, we use the
RequestCallBack class to create such a callback handler.

Referring to the listing below, note that we will need to implement the onError() and
onResponseReceived() methods to handle both situations. Another thing to note is
that even when a response is successfully received, we still need to check the returned
status code to ensure that it is 200 – which indicates a successful response.

A “Word of Wisdom” retrieved from the Response object will then be displayed in a
DialogBox.

For the complete program source code up till this stage, please refer to the Eclipse
project: SnakeAndLadderPrj-04.

Page 20 / 23
code::XtremeApps::
Google Web Toolkit Training

1.7.5. To emphasize the asynchronous aspect of the communication, we purposely delay the
response by a few seconds (on the server-side). Note that during these few seconds of
delay, you can still continue with your game of Snake and Ladder.

Page 21 / 23
code::XtremeApps::
Google Web Toolkit Training

Step 1.8 – Running GWT application in Hosted and Web mode


GWT supports running a GWT application in either Hosted mode or Web mode. As stated in
GWT Developer Guide:

You will spend most of your development time working in hosted mode, which means
that you are interacting with your GWT application without it having been translated into
JavaScript. Anytime you edit, run, and debug applications from a Java integrated
development environment (IDE), you are working in hosted mode. When running in
hosted mode, the Java Virtual Machine (JVM) is actually executing your
application code as compiled Java bytecode, using GWT plumbing to automate
an embedded browser window. By remaining in this traditional "code-test-debug"
cycle, hosted mode is by far the most productive way to develop your application
quickly.

In hosted mode, since the code runs in the JVM, that means when your code performs an action
like handling a mouse event, you get full-featured Java debugging, with exceptions and the
advanced debugging features of IDEs like Eclipse we are using now.

As for running of your application in Web mode, GWT Developer Guide states:

As you move from development into end-to-end testing and production, you will begin
to interact with your application in web mode more often. Web mode refers to
accessing your application from a normal browser -- where it runs as pure
JavaScript -- as it is ultimately intended to be deployed.

To create a web mode version of your module, you compile it using either the
"Compile/Browse" button available in the hosted browser window or the command-line
compiler com.google.gwt.dev.GWTCompiler.

Web mode demonstrates what makes GWT unusual: when your application is
launched in web mode, it runs completely as JavaScript and does not require any
browser plug-ins or JVM.

1.8. Deployment for Web mode


1.8.1. As stated above, we can click on the “Compile/Browse” button available in the hosted
browser to trigger the GWT compilation process + the running of the GWT application
in a normal browser.

Page 22 / 23
code::XtremeApps::
Google Web Toolkit Training

1.8.2. Note that after the GWT compilation process, the compiled code will be place in a
“www” directory within the Eclipse project.

Conclusions
Finally, we have come to an end to this training. It is hoped that you will find this training a
useful experience in learning a few fundamentals of GWT development. However, there are
still many GWT development concepts which are not covered in this short training. To further
your GWT knowledge, please refer to the following references which I have found very useful
and informative during the course of my preparation of this training guide.

References:
• Official Google Web Toolkit Developer Guide
http://code.google.com/webtoolkit/documentation/com.google.gwt.doc.DeveloperGuide.html
• Official Google Web Toolkit Class Reference
http://code.google.com/webtoolkit/documentation/gwt.html
• GWT in Action, authored by Robert Hanson and Adam Tacy
http://www.manning.com/hanson/
• Agile AJAX : 36 GWT Tutorials
http://blogs.pathf.com/agileajax/2007/07/36-gwt-tutorial.html
• Google™ Web Toolkit Solutions: Cool & Useful Stuff, by David Geary
http://safari.awprofessional.com/0131584650?tocview=true

About the author:

Ho Wee Chong is currently a lecturer teaching in the School of Information Technology,


Nanyang Polytechnic of Singapore.

Page 23 / 23

You might also like