English | Site Directory

Google Web Toolkit

  • New!
  • Grab the release candidate for GWT 1.5 and take it for a test drive! You can find it on the downloads page.
  • The documentation for GWT 1.5 can be found here.

Fundamentals

Core GWT concepts such as compiling Java source into JavaScript, debugging, cross-browser support, and defining modules.

Contents

  • GWT Compiler
    A compiler that transforms your working Java application into an equivalent JavaScript application.
    • Language Support
      GWT supports most core Java 1.4 language semantics, but there are a few differences you'll want to be aware of.
    • Runtime Library Support
      GWT emulates a basic set of the standard Java library classes.
  • Cross-browser Support
    The architecture of GWT makes it easy to support multiple browsers with a single code base.
  • Debugging in Hosted Mode
    An embedded DHTML browser lets you run and debug applications directly in any Java development environment before being translated into JavaScript.
  • Deployment in Web Mode
    Compile your application into JavaScript for easy deployment.
  • HTML Host Pages
    A host page is an HTML document that includes a GWT module.
  • Client-side Code
    "Client-side" refers to source code that is intended to be translated and run in a web browser as JavaScript.
  • Server-side Code
    "Server-side" refers to source code that is not intended to be translated and will only run on a server as bytecode.
  • Project Structure
    GWT projects are built from a recommended package layout.
  • Modules
    Modules are XML files that contain settings related to your application or library.
  • Command-line Tools
    Useful command-line tools for getting started.

GWT Compiler

The heart of GWT is a compiler that converts Java source into JavaScript, transforming your working Java application into an equivalent JavaScript application. Generally speaking,
  1. If your GWT application compiles and runs in hosted mode as you expect
  2. And GWT compiles your application into JavaScript output without complaint,
  3. Then your application will work the same way in a web browser as it did in hosted mode.
The GWT compiler supports the vast majority of the Java language itself. The GWT runtime library emulates a relevant subset of the Java runtime library.

Language Support

GWT compiles Java source that is compatible with J2SE 1.4.2 or earlier.
  • Intrinsic types
    byte, char, short, int, long, float, double, Object, String, and arrays are supported. However, there is no 64-bit integral type in JavaScript, so variables of type long are mapped onto JavaScript double-precision floating point values. To ensure maximum consistency between hosted mode and web mode, we recommend that you use int variables.
  • Exceptions
    try, catch, finally and user-defined exceptions are supported as normal, although Throwable.getStackTrace() is not supported for web mode. See Throwable for additional details.
  • Assertions
    The GWT compiler parses Java assert statements, but it does not emit code JavaScript code for them.
  • Multithreading and Synchronization
    JavaScript interpreters are single-threaded, so while GWT silently accepts the synchronized keyword, it has no real effect. Synchronization-related library methods are not available, including Object.wait(), Object.notify(), and Object.notifyAll()
  • Reflection
    For maximum efficiency, GWT compiles your Java source into a monolithic script, and does not support subsequent dynamic loading of classes. This and other optimizations preclude general support for reflection. It is possible to query an object for its class name using GWT.getTypeName(Object).
  • Finalization
    JavaScript does not support object finalization during garbage collection, so GWT isn't able to be honor Java finalizers in web mode.
  • Strict Floating-Point
    The Java language specification precisely defines floating-point support, including single-precision and double-precision numbers as well as the strictfp keyword. GWT does not support the strictfp keyword and can't ensure any particular degree of floating-point precision in translated code, so you may want to avoid calculations in client-side code that require a guaranteed level of floating-point precision.

Runtime Library Support

GWT supports only a small subset of the classes available in the Java 2 Standard and Enterprise Edition libraries, as these libraries are quite large and rely on functionality that is unavailable within web browsers. To find out exactly which classes and methods are supported for core Java runtime packages, see the API reference for java.lang and java.util, which lists supported classes and contains notes on behavioral differences from the standard Java runtime.

Some specific areas in which GWT emulation differs from the standard Java runtime:

  • Regular Expressions
    The syntax of Java regular expressions is similar, but not identical, to JavaScript regular expressions. For example, the replaceAll and split methods use regular expressions. So, you'll probably want to be careful to only use Java regular expressions that have the same meaning in JavaScript.
  • Serialization
    Java serialization relies on a few mechanisms that are not available in compiled JavaScript, such as dynamic class loading and reflection. As a result, GWT does not support standard Java serialization. Instead, GWT has an RPC facility that provides automatic object serialization to and from the server for the purpose of invoking remote methods.

Tip
You'll save yourself a lot of frustration if you make sure that you use only translatable classes in your client-side code from the very beginning. To help you identify problems early, your code is checked against the JRE emulation library whenever you run in hosted mode. As a result, most uses of unsupported libraries will be caught the first time you attempt to run your application. So, run early and often.

Cross-browser Support

GWT shields you from worrying too much about cross-browser incompatibilities. If you stick to built-in widgets and composites, your applications will work similarly on the most recent versions of Internet Explorer, Firefox, and Safari. (Opera, too, most of the time.) DHTML user interfaces are remarkably quirky, though, so make sure to test your applications thoroughly on every browser.

Whenever possible, GWT defers to browsers' native user interface elements. For example, GWT's Button widget is a true HTML <button> rather than a synthetic button-like widget built, say, from a <div>. That means that GWT buttons render appropriately in different browsers and on different client operating systems. We like the native browser controls because they're fast, accessible, and most familiar to users.

When it comes to styling web applications, CSS is ideal. So, instead of attempting to encapsulate UI styling behind a wall of least-common-denominator APIs, GWT provides very few methods directly related to style. Rather, developers are encouraged to define styles in stylesheets that are linked to application code using style names. In addition to cleanly separating style from application logic, this division of labor helps applications load and render more quickly, consume less memory, and even makes them easier to tweak during edit/debug cycles since there's no need to recompile for style tweaks.

Debugging in Hosted Mode

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.

To launch a hosted mode session, your startup class should be com.google.gwt.dev.GWTShell, found in gwt-dev-windows.jar (or gwt-dev-linux.jar).

Tip
In hosted mode, the GWT development shell looks for modules (and therefore client-side source) using the JVM's classpath. Make sure to add your source directories first in your classpath when running the development shell.

Deployment in Web Mode

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.

HTML Host Pages

Any HTML page containing the proper incantation can include code created with GWT, referred to as a host page. A typical HTML host page looks like this:
 <html>
  <head>
  
    <!-- Properties can be specified to influence deferred binding -->
    <meta name='gwt:property' content='locale=en_UK'>
    
    <!-- Stylesheets are optional, but useful -->
    <link rel="stylesheet" href="Calendar.css">
    
    <!-- Titles are optional, but useful -->
    <title>Calendar App</title>
    
  </head>
  <body>
   
    <!-- The fully-qualified module name, followed by 'nocache.js' -->
    <script language="javascript" src="com.example.cal.Calendar.nocache.js"></script>
    
    <!-- Include a history iframe to enable full GWT history support -->
    <!-- (the id must be exactly as shown)                           -->
    <iframe src="javascript:''" id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>
    
  </body>
 </html>
 
The structure was designed to make it easy to add GWT functionality to existing web applications with only minor changes.

Client-side Code

Your application is sent across a network to a user, where it runs as JavaScript inside his or her web browser. Everything that happens within your user's web browser is referred to as client-side processing. When you write client-side code that is intended to run in the web browser, remember that it ultimately becomes JavaScript. Thus, it is important to use only libraries and Java language constructs that can be translated.

Server-side Code

Everything that happens within your server computer is referred to as server-side processing. When your application needs to interact with your server (for example, to load or save data), it makes a client-side request (from the browser) across the network using a remote procedure call (RPC). While processing an RPC, your server is executing server-side code.
Tip
GWT doesn't 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.

Project Structure

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:

Package Purpose
com/example/cal/The project root package contains module XML files
com/example/cal/client/Client-side source files and subpackages
com/example/cal/server/Server-side code and subpackages
com/example/cal/public/Static resources that can be served publicly

and examples files would be arranged like so:

FilePurpose
com/example/cal/Calendar.gwt.xmlA common base module for your project that inherits com.google.gwt.user.User module
com/example/cal/CalendarApp.gwt.xmlInherits the com.example.cal.Calendar module (above) and adds an entry point class
com/example/cal/CalendarTest.gwt.xmlA module defined by your project
com/example/cal/client/CalendarApp.javaClient-side Java source for the entry-point class
com/example/cal/client/spelling/SpellingService.javaAn RPC service interface defined in a subpackage
com/example/cal/server/spelling/SpellingServiceImpl.javaServer-side Java source that implements the logic of the spelling service
com/example/cal/public/Calendar.htmlAn HTML page that loads the calendar app
com/example/cal/public/Calendar.cssA stylesheet that styles the calendar app
com/example/cal/public/images/logo.gifA logo
Tip
The easiest way to create a GWT project from scratch is to use the projectCreator script.

Modules

Individual units of GWT configuration are XML files called modules. A module bundles together all the configuration settings that your GWT project needs, namely
  • Inherited modules
  • An entry point application class name; these are optional, although any module referred to in HTML must have at least one entry-point class specified
  • Source path entries
  • Public path entries
  • Deferred binding rules, including property providers and class generators
Modules may appear in any package in your classpath, although it is strongly recommended that they appear in the root package of a standard project layout.

Entry-Point Classes

A module entry-point is any class that is assignable to EntryPoint and that can be constructed without parameters. When a module is loaded, every entry point class is instantiated and its EntryPoint.onModuleLoad() method gets called.

Source Path

Modules can specify which subpackages contain translatable source, causing the named package and its subpackages to be added to the source path. Only files found on the source path are candidates to be translated into JavaScript, making it possible to mix client-side and server-side code together in the same classpath without conflict.

When module inherit other modules, their source paths are combined so that each module will have access to the translatable source it requires.

Public Path

Modules can specify which subpackages are public, causing the named package and its subpackages to be added to the public path. When you compile your application into JavaScript, all the files that can be found on your public path are copied to the module's output directory. The net effect is that user-visible URLs need not include a full package name.

When module inherit other modules, their public paths are combined so that each module will have access to the static resources it expects.

Module XML Format

Modules are defined in XML files whose file extension is .gwt.xml. Module XML files should reside in your project's root package.

If you are using the standard project structure, your module XML can be as simple as this:

 <module>
    <inherits name="com.google.gwt.user.User"/>
    <entry-point class="com.example.cal.client.CalendarApp"/>
 </module>

Loading Modules

Module XML files are found on the Java classpath, referenced by their logical module names from host pages and by being inherited by other modules.

Modules are always referred to by their logical names. The logical name of a module is of the form pkg1.pkg2.ModuleName (although any number of packages may be present) and includes neither the actual file system path nor the file extension. For example, the logical name of a module XML file located at

~/src/com/example/cal/Calendar.gwt.xml
is
com.example.cal.Calendar

Available Elements

<inherits name="logical-module-name"/>
Inherits all the settings from the specified module as if the contents of the inherited module's XML were copied verbatim. Any number of modules can be inherited in this manner.
<entry-point class="classname"/>
Specifies an entry point class. Any number of entry-point classes can be added, including those from inherited modules.
<source path="path"/>
Adds packages to the source path by combining the package in which the module XML is found with the specified path to a subpackage. Any Java source file appearing in this subpackage or any of its subpackages is assumed to be translatable.

If no <source> element is defined in a module XML file, the client subpackage is implicitly added to the source path as if <source path="client"> had been found in the XML. This default helps keep module XML compact for standard project layouts.

<public path="path"/>
Adds packages to the public path by combining the package in which the module XML is found with the specified path to identify the root of a public path entry. Any file appearing in this package or any of its subpackages will be treated as a publicly-accessible resource. The <public> element supports pattern-based filtering to allow fine-grained control over which resources get copied into the output directory during a GWT compile.

If no <public> element is defined in a module XML file, the public subpackage is implicitly added to the public path as if <public path="public"> had been found in the XML. This default helps keep module XML compact for standard project layouts.

<servlet path="url-path" class="classname"/>
For convenient RPC testing, this element loads a servlet class mounted at the specified URL path. The URL path should be absolute and have the form of a directory (for example, /spellcheck). Your client code then specifies this URL mapping in a call to ServiceDefTarget.setServiceEntryPoint(String). Any number of servlets may be loaded in this manner, including those from inherited modules.
<script src="js-url"/>
Automatically injects the external JavaScript file located at the location specified by src. See automatic resource inclusion for details.
<stylesheet src="css-url"/>
Automatically injects the external CSS file located at the location specified by src. See automatic resource inclusion for details.
<extend-property name="client-property-name" values="comma-separated-values"/>
Extends the set of values for an existing client property. Any number of values may be added in this manner, and client property values accumulate through inherited modules. You will likely only find this useful for specifying locales in internationalization.

Automatic Resource Inclusion

Modules can contain references to external JavaScript and CSS files, causing them to be automatically loaded when the module itself is loaded.

Including External JavaScript

Script inclusion is a convenient way to automatically associate external JavaScript files with your module. Use the following syntax to cause an external JavaScript file to be loaded into the host page before your module entry point is called.
<script src="js-url"/>
The script is loaded into the namespace of the host page as if you had included it explicitly using the HTML <script> element. The script will be loaded before your onModuleLoad() is called.

Including External Stylesheets

Stylesheet inclusion is a convenient way to automatically associate external CSS files with your module. Use the following syntax to cause a CSS file to be automatically attached to the host page.
<stylesheet src="css-url"/>
You can add any number of stylesheets this way, and the order of inclusion into the page reflects the order in which the elements appear in your module XML.

Inclusion and Module Inheritance

Module inheritance makes resource inclusion particularly convenient. If you wish to create a reusable library that relies upon particular stylesheets or JavaScript files, you can be sure that clients of your library have everything they need automatically by inheriting from your module.
Tip
Versions of GWT prior to 1.4 required a script-ready function to determine when an included script was loaded. This is no longer required; all included scripts will be loaded when your application starts, in the order in which they are declared.

Filtering Public Packages

The <public> element supports certain attributes and nested elements to allow pattern-based inclusion and exclusion. It follows the same rules as Ant's FileSet element. Please see the documentation for FileSet for a general overview.

The <public> element does not support the full FileSet semantics. Only the following attributes and nested elements are currently supported:

  • The includes attribute
  • The excludes attribute
  • The defaultexcludes attribute
  • The casesensitive attribute
  • Nested include tags
  • Nested exclude tags
Other attributes and nested elements are not supported.

Important

The default value of defaultexcludes is true. By default, the patterns listed here are excluded.

Command-line Tools

GWT comes with a few handy command-line tools to get you up and running quickly. They are also useful for adding new things to existing projects. For example, projectCreator could be used to make an Eclipse project for one of the samples that comes with GWT.

projectCreator

Generates an Ant buildfile or Eclipse project.

projectCreator [-ant projectName] [-eclipse projectName] [-out dir] [-overwrite] [-ignore]

-antGenerate an Ant buildfile to compile source (.ant.xml will be appended)
-eclipseGenerate an eclipse project
-outThe directory to write output files into (defaults to current)
-overwriteOverwrite any existing files
-ignoreIgnore any existing files; do not overwrite

Example

 ~/Foo> projectCreator -ant Foo -eclipse Foo
 Created directory src
 Created directory test
 Created file Foo.ant.xml
 Created file .project
 Created file .classpath

Running ant -f Foo.ant.xml will compile src into bin. The buildfile also contains a package target for bundling the project into a jar.

.project can be imported into an Eclipse workspace.

applicationCreator

Generates a starter application and scripts for launching hosted mode and compiling to JavaScript.

applicationCreator [-eclipse projectName] [-out dir] [-overwrite] [-ignore] className

-eclipseCreates a debug launch configuration for the named eclipse project
-outThe directory to write output files into (defaults to current)
-overwriteOverwrite any existing files
-ignoreIgnore any existing files; do not overwrite
classNameThe fully-qualified name of the application class to create

Example

 ~/Foo> applicationCreator -eclipse Foo com.example.foo.client.Foo
 Created directory src/com/example/foo/client
 Created directory src/com/example/foo/public
 Created file src/com/example/foo/Foo.gwt.xml
 Created file src/com/example/foo/public/Foo.html
 Created file src/com/example/foo/client/Foo.java
 Created file Foo.launch
 Created file Foo-shell
 Created file Foo-compile
Running Foo-shell brings up the new app in hosted mode. Foo-compile translates the Java app to JavaScript, creating a web folder under www. Foo.launch is a launch configuration for Eclipse.

junitCreator

Generates a JUnit test and scripts for testing in both hosted mode and web mode.

junitCreator -junit pathToJUnitJar [-eclipse projectName] [-out dir] [-overwrite] [-ignore] className

-junitSpecify the path to your junit.jar (required)
-moduleSpecify name of the application module to use (required)
-eclipseCreates a debug launch configuration for the named eclipse project
-outThe directory to write output files into (defaults to current)
-overwriteOverwrite any existing files
-ignoreIgnore any existing files; do not overwrite
classNameThe fully-qualified name of the test class to create

Example

 ~/Foo> junitCreator -junit /opt/eclipse/plugins/org.junit_3.8.1/junit.jar
        -module com.example.foo.Foo
        -eclipse Foo com.example.foo.client.FooTest
 Created directory test/com/example/foo/test
 Created file test/com/example/foo/client/FooTest.java
 Created file FooTest-hosted.launch
 Created file FooTest-web.launch
 Created file FooTest-hosted
 Created file FooTest-web
Running FooTest-hosted tests as Java bytecode in a JVM. FooTest-web tests as compiled JavaScript. The launch configurations do the same thing in Eclipse.

i18nCreator

Generates internationalization scripts for static internationalization, along with sample properties files.

i18nCreator [-eclipse projectName] [-out dir] [-overwrite] [-ignore] [-createMessages] interfaceName

-eclipseCreates a debug launch config for the named Eclipse project
-outThe directory to write output files into (defaults to current)
-overwriteOverwrite any existing files
-ignoreIgnore any existing files; do not overwrite
-createMessagesGenerate scripts for a Messages interface rather than a Constants one
interfaceNameThe fully-qualified name of the interface to create

Example

 ~/Foo> i18nCreator -eclipse Foo -createMessages com.example.foo.client.FooMessages
 Created file src/com/example/foo/client/FooMessages.properties
 Created file FooMessages-i18n.launch
 Created file FooMessages-i18n
 
 ~/Foo> i18nCreator -eclipse Foo com.example.foo.client.FooConstants
 Created file src/com/example/foo/client/FooConstants.properties
 Created file FooConstants-i18n.launch
 Created file FooConstants-i18n

Running FooMessages-i18n will generate an interface from FooMessages.properties that extends Messages (The messages will take parameters, substituting {n} with the nth parameter).

Running FooConstants-i18n will generate an interface from FooConstants.properties that extends Constants (The constants will not take parameters).

The launch configurations do the same thing as the scripts, from within Eclipse.

benchmarkViewer

Reads benchmark reports from a folder and displays their results, including various visualizations.

benchmarkViewer [path]

pathSpecify the path to the XML benchmark reports. If the path is not specified, it defaults to the current working directory.

Example

 ~/Foo> benchmarkViewer my/benchmark/results
 
Looks for report XML files in the folder my/benchmark/results and displays them in the viewer.