2. Google Web Toolkit (GWT) is a Java to JavaScript
cross-compiler.
It takes Java code and compiles it into JavaScript
versions for all the major browsers in a single
compilation step.
GWT is hence statically compiled strongly typed
Java language.
GWT includes debugging Java bytecode in a
simulated browser environment, set of core UI
and layout widgets, RPC system for handling
web server communications and
internationalization support.
3. GWT allows the client to maintain state and
even perform computations locally, with a full
data model, without requiring a trip to the
server for every update to the interface.
GWT also provides a rich platform in terms of a
wide variety of UI elements and capabilities:
sliders, reflections, drag-and-drop
support, suggest boxes and data-bound tables.
GWT is not a framework itself but basis for the
application framework.
GWT provides the components required for Ajax
applications.
4. GWT Java compiler takes Java code and
compiles it into JavaScript.
By defining GWT compile tasks into modules,
the compiler can perform more analysis on the
code as it’s processed, and branch into multiple
compilation artifacts for different output
targets.
During compilation one can specify differing
implementations based on known parameters,
such as user agent or client browser.
5. It enables to implement UI elements in Java and
then using a browser-specific implementation of
the core DOM to build out the native browser
elements as needed by the higher-level Java
layer.
GWT UI layer provides a wide variety of layout-
related panels, data representation constructs
such as Tree and Grid, and a set of user input
elements.
It also provides new optimized UI elements that
draw from the power of the plugin-capable
compiler, such as the ImageBundle.
6. The RPC system allows for serialization and
deserialization of Java objects from server-side
implementations of remote services, which can then
be called asynchronously from the client.
The compiler generates code during the compilation
step to handle the serialization at a low level.
Serialized objects are versioned and mapped at
compile time providing two major advantages:
1) The client and server agreement can be
guaranteed as new versions are deployed.
2) The server implementation can compress the
state of Java objects down to arrays of JavaScript
primitives.
7. Additional utilities include support for
additional ways to communicate with servers,
internationalization (i18n) tools, a history
management system, and testing support.
GWT provides several client-side libraries for
going beyond the standard GWT RPC and
instead communicating with XML and JSON-
based services.
GWT includes compile-time-checked
internationalization library, history management
system for bookmarking and deep linking, and a
formal testing support.
8. The GWT shell allows developers to test their
application in a browser while executing the
native Java bytecode.
It gives the ability to use all the other Java tools
to inspect the application, including
profilers, step-through debugging, and JTI-
based monitors.
The hosted mode browser, with an embedded
Apache Tomcat server makes possible to test
the compiled JavaScript with Junit.
9. GWT projects are defined in terms of modules,
composed of resources, configuration, and
source.
The module configuration defines compile-time
information about a project and specifies
resources needed at runtime.
The modules also make possible a rich
inheritance mechanism.
A module defines the starting point of the
project which is known as entry point.
10. Entry point classes are coded in Java and are
referenced by a module definition and compiled
to JavaScript.
Modules themselves and the entry points they
define, are invoked through a <script> reference
on an HTML page, known as a host page.
Host pages invoke GWT projects and also support
a few special <meta> tags that can be used to
tweak things.
The three main components of a GWT project
are: a module configuration file, an entry point
class, and an HTML host page.
11. The GWT module system allows application
components to package the client-side application
code, server-side service implementations, and assets
such as graphics or CSS file into an easily
redistributable package.
A module is defined by an XML file packaged with the
Java source implementing the module.
Typical XML file declares primary elements as:
inherited modules, servlet deployments, compiler
plugins, and entry points.
The <inherits> tag tells GWT to inherit the core module
Inheriting a module brings in all the elements of the
module, not just source code.
12. The package folder (For example, com.manning)
-> Module.gwt.xml (The module definition file)
-> client: The client package containing code
that will be crosscompiled to JavaScript
-> public: Folder containing assets used by the
module (images, CSS files, other resources)
-> server: The package containing server-side
implementation code
-> rebind: The package containing compile-
time code (generators)
13. The HTML host page contains a couple of special
elements needed to activate a GWT application.
First is a reference to a bootstrap (nocache) JavaScript file
generated for every module.
The nocache file detects the appropriate version of the
application module, based on the user agent and other
factors, and loads up the monolithically compiled
application.
The *.nocache.js and *-xs.nocache.js are two files send
to the client without HTTP-level caching enabled.
All other files generated by GWT are named based on a
hash of the source code.
The two nocache files determine which hashed version to
be loaded when the page is requested.
14. The cross-site xs version of the nocache file is
used by other domains that includes the
application.
It allows remote domains (even from different
host) to communicate with the server-side
resources.
When a module nocache script (either standard
or cross-site) is loaded from a host page, the
remainder of the GWT bootstrap process is
invoked and an entry point class is loaded.
15. An entry point class is a simple client-side class that
implements the com.google.gwt.core.client.EntryPoint
interface, which defines a single method:
onModuleLoad().
The GWT’s RootPanel class enables application to access
the HTML host page.
Calling RootPanel.get() returns a default container that
is inserted just before the ending </body> tag in the
HTML page.
public class Calculator implements EntryPoint {
public void onModuleLoad() {
RootPanel.get().add(newCalWidget("calculator"));
} }
16. The shell is composed of three main parts: a
logging console, an embedded Tomcat
server, and the hosted mode browser.
The GWT shell console provides an enhanced
logging interface and centralized GUI as a GWT
dashboard.
The hosted mode browser is capable of invoking
Java classes directly on browser events, rather
than requiring a compilation to JavaScript; thus
using a standard Java debugger to work with the
Ajax code, instead of relying solely on compiled
JavaScript for testing and interaction.
17. GWT Shell Description
-port Runs an embedded Tomcat instance on the specified port (defaults to
8888).
-noserver Prevents the embedded Tomcat server from running, even if a port is
specified.
-whitelist Allows the user to browse URLs that match the specified regular
expressions (comma or space separated).
-blacklist Prevents the user from browsing URLs that match the specified regular
expressions (comma or space separated).
-logLevel The logging level: ERROR, WARN, INFO, TRACE, DEBUG, SPAM, or ALL.
-gen The directory into which generated files will be written for review.
-out The directory to which output files will be written (defaults to current).
-style Script output style: OBF[uscated], PRETTY, or DETAILED (defaults to OBF).
url Launches the specified URL automatically.
18. The GWT shell console is a hierarchical logging display.
Log Level Description
ERROR Shows only critical errors in the GWT shell code.
WARN Shows uncaught exceptions in user code. WARN and ERROR information
are displayed in red in the shell window.
INFO Shows server startup info and invocations into specific GWT modules.
This mode is displayed by default simply as“Starting HTTP on port 8888.”
TRACE Shows each request logged, as well as module instantiations, their
locations on the class path, and the time. Displayed in gray in the shell.
DEBUG Shows the binding of classes inside the GWT shell for code invocations
and URL mapping. It is displayed in green in the shell window.
SPAM Shows all ClassLoader events and invocations to native JavaScript. It is
displayed in teal in the shell window
ALL Shows all logging information.
19. It operates as a test browser harness that directly
invokes Java binary code in response to the browser
events.
It allows to view code changes immediately and to
perform step-through debugging of code between
the client and server sides.
The hosted mode browser also provides a shortcut
for executing the compiled JavaScript version of the
application using the Compile/Browse button with
GWT_EXTERNAL_BROWSER defined in environment.
The hosted mode browser can be used apart from
the GWT shell’s Tomcat instance with the -noserver
option.
20. The GWT compiler is a Java source to JavaScript
source translator.
The GWT compiler optimizes the application at
compile time by compressing javascript naming
and pruning unused classes.
GWT examines code and only provides
serialization for the classes were explicitly
needed.
GWTCompiler [-logLevel level] [-gen dir] [-out
dir] [-treeLogger] [-style style] module
21. Option Description
-logLevel The logging level (during compliation): ERROR, WARN,
INFO, TRACE, DEBUG, SPAM, or ALL.
-gen The directory into which generated files will be written
for review.
-out The directory to which output files will be written
(defaults to the current directory).
-treeLogger Logs output in a graphical tree view (hierarchical logging
information).
-style The script output style: OBF[uscated], PRETTY, or
DETAILED (defaults to OBF).
module The name of the module to compile.
22. The –style command-line option for the GWT
complier is used to control the generated
JavaScript.
OBF—Obfuscated mode. This is a non-human-
readable, compressed version suitable for
production use. Names are compressed and
whitespaces are cleaned.
PRETTY—Pretty-printed JavaScript with
meaningful names, while collisions are resolved
with suffixes.
DETAILED—Pretty-printed JavaScript with fully
qualified names (for both class and methods).
23. GWT interacts with native JavaScript, through the
JavaScript Native Interface (JSNI).
The names of the classes and methods in their JavaScript
form aren’t guaranteed, even for different compilations of
the same application.
The special syntax with JSNI enables invocation
of, Javascript objects from java code and compiled Java
classes from within JavaScript, has following limitations.
When JavaScript API is exposed for external use, the
references should be created for calls into GWT code using
JSNI registrations.
The Javascript naming in the object hash is unreliable since
the method names are not reliable.
Potential conflicts can occur with javascript libraries while
publishing using PRETTY setting.
24. The GWT compiler is currently limited to J2SE
1.4 syntactical structures.
GWT JRE emulation library supports limited
subset of Java classes.
The GWT compiler helps by optimizing the
JavaScript it emits to include only classes and
methods that are on the execution stack of the
module and by using native browser functions
wherever possible.
25. The compiler identifies which combinations of GWT
module definition files need to be built.
GWT builds specific versions of the
application, each exactly targeted to the needs of
the client (user agent, locale, so on).
A particular build combination is defined in the
GWT module definition using a <defineproperty>
tag.
Each of the build combination is processed as a
build of the final JavaScript emitted by GWT.
GWT can switch implementations of classes based
on properties using the <replace-with> tag in the
module definition.
26. The JavaScript snippet contained within the <property-
provider> tag determines which of the
implementations defined will be used when GWT
starts.
The basic DOM class is implemented with the same
interface for each of the browsers, providing a core set
of operations on which cross-platform code can easily
be written.
The DOM object is a singleton exposing static methods
that are called by applications, like GWT.create().
The technique of identifying build combinations and
then spinning off into specific implementations during
the compile process is known as deferred binding.
27. Each variation or axis added becomes a
combinatory compile.
GWT generates any client-side code using the
generator metaprogramming model.
GWT’s compiler includes a code generation or
metaprogramming facility that allows to generate
code based on module properties at compile time.
The i18n (internationalization) module defines
several no-method interfaces which can be
extended to define Constants, Messages, or
Dictionary classes using the <extend-property>
tag.
28. In order to integrate existing JavaScript or extend or
add lower-level components, GWT includes JSNI .
It allows to define method implementations on a Java
class using JavaScript.
The javascript implementation lives right in the Java
file, surrounded by a special /*- -*/ comment syntax.
GWT takes all the Java files, whether provided or
generated, and the JSNI method
implementations, and examines the call tree, pruning
unused methods and attributes.
Then it transforms all of this into a number of unique
JavaScript files, targeted very specifically at each
needed axis.
29. ApplicationCreator is provided by GWT to create the
default starting points and layout for a GWT project.
It supports command-line params as:
ApplicationCreator [-eclipse projectName] [-out dir]
[-overwrite] [-ignore] className
Parameter Description
-eclipse Creates a debug launch configuration for the named eclipse project.
-out The directory to which output files will be written (defaults to the
current directory).
-overwrite Overwrites any existing files.
-ignore Ignores any existing files; does not overwrite.
className The fully qualified name of the application class to be created.
30. The package name is represented in the structure
as a series of subdirectories in the src tree, with
separate client and public subdirectories within.
The client directory (source path) is intended for
resources that will be compiled into JavaScript.
The client items are translatable, or
serializable, and will ultimately be downloaded to a
client browser.
The public directory (public path) denotes files that
will also be distributed to the client, but that do not
require compilation and translation to JavaScript
which includes CSS, images, static HTML etc.
31.
32. Along with the module definition, entry
point, and host page, shortcut scripts listed
below are also needed for a GWT project.
File Name Purpose
GWT module file ProjectName.gwt.xml Defines the project configuration
Entry point class ProjectName.java Starting class invoked by the
module.
Host page ProjectName.html Initial HTML page that loads
the module.
GWTShell shortcut
invoker script
ProjectName-shell.sh Invokes GWTShell for the project.
GWTCompiler shortcut
invoker script
ProjectName-compile.sh Invokes GWTCompiler for
the project.
33. A host page is initial HTML page that invokes a GWT application.
A host page contains a script tag that references a special GWT
JavaScript file, Module.nocache.js which kicks off the GWT
application loading process.
Meta tag Syntax Purpose
gwt:module <meta name="gwt:module"
content="_module-name_">
Specifies the module to be loaded (pre
GWT 1.4).
gwt:property <meta name="gwt:property"
content="_name_=_value_">
Statically defines a deferred binding
client property.
gwt:onPropertyErrorFn <meta
name="gwt:onPropertyError
Fn" content="_fnName_">
Specifies the name of a function to call
if a client property is set to an invalid
value (i.e. no matching compilation will
be found).
Specifies the name of a function to call
if an exception happens during
bootstrapping or if a module throws an
exception out of onModuleLoad();
function takes a message parameter.
gwt:onLoadErrorFn <meta
name="gwt:onLoadErrorFn"
content="_fnName_">
34. Modules are execution units which enable to separate
the discreet areas of responsibility.
Modules enable setting of configuration and
properties, provide resources for projects, enable
inheritance, give the compiler hints, and play a central
role in the bootstrapping process.
The Module.gwt.xml is a module descriptor for the
project at the top-level and, provides a means to
define resource locations and structure.
A default generated module file contains <inherits>
element which includes the configuration for another
named GWT module in the current definition, and
<entry-point> element which defines a class that kicks
things off and moves from configuration to code.
35. Module element Description
<inherits> Identifies additional GWT modules that should be inherited into the current
module.
<entry-point> Specifies which EntryPoint class should be invoked when starting a project.
<source> Identifies where the source code that should be translated into JavaScript by
the GWT compiler is located.
<public> Identifies where assets that are not translatable source code, such as images
and CSS files, are located.
<script> Injects a script element into a GWT module, ensuring it is present
when inherited.
<stylesheet> Injects a stylesheet into a GWT module, ensuring it is present when inherited
<servlet> Specifies the path to GWT RPC Service Servlet resources.
<define-property> Initially defines properties.
<set-property> Sets property values; for example, it is used in the UserAgent module to
define the set of supported browsers.
<extend-property> Specifies property value extensions; often used to specify locale information.
<replace-with> Replaces components at runtime based on a decision process, such as
different implementations for different browser versions.
36. An entry point class is the first project-specific
code invoked by the GWT application.
Entry point is were the first browser-based
element is accessed by the static
RootPanel.get() method.
The RootPanel is a default container that is
inserted directly after the HTML body tag.
With the RootPanel as the reference, other
elements can be inserted into the project.
37. The model should be completely unaware of the view
and controller, and the pattern can be applied on many
different levels within an application.
In MVC, the model can be equipped to alert observers
of changes within it, using the Observer pattern.
The model is reusable part and does not update or
have any direct knowledge of the view.
The view typically has a reference to the
controller, while the controller has no direct references
back to the view, and simply updates the model.
MVC can be applied with GWT, and it can happen on
many different levels, with individual widgets having
their own encapsulated MVC.
38. In MVC, widgets begin with the view elements,
starting with the layout.
Widgets are built from layout panels, input
elements, events, data objects, and various
combinations.
Widgets are capable of being inserted or
removed from the screen, in a single page, on
the client side.
A ClickListener when attached to the button,
gets the control when the buttons are clicked,
and it invokes a controller method.
39. import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class CalculatorWidget extends VerticalPanel {
private TextBox display;
public CalculatorWidget(final String title) {
super();
final CalculatorData data = new CalculatorData();
final CalculatorController controller =
new CalculatorController(data);
}
40. VerticalPanel p = new VerticalPanel();
p.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
p.setStyleName(CalculatorConstants.STYLE_PANEL);
Grid g = new Grid(4, 5); // rows and columns grid
g.setStyleName(CalculatorConstants.STYLE_GRID);
final Button zero = new ButtonDigit(controller, "0"); // extends Button class
g.setWidget(3, 0, zero); …. // more digit buttons
final Button divide = new ButtonOperator(controller, new
OperatorDivide()); // ButtonOperator extends Button class and implements ClickListener
g.setWidget(0, 3, divide); …. // more operation buttons
final Button clear = new Button(CalculatorConstants.CLEAR);
clear.addClickListener(new ClickListener() {
public void onClick(Widget sender) { controller.processClear(); }
});
clear.setStyleName(CalculatorConstants.STYLE_BUTTON);
g.setWidget(2, 4, clear);
43. public interface CalculatorChangeListener { public void onChange(CalculatorData data); }
public interface CalculatorChangeNotifier {
public void addChangeListener(final CalculatorChangeListener listener);
}
public class CalculatorData implements CalculatorChangeNotifier {
private String display;
private double buffer;
private boolean initDisplay;
private boolean lastOpEquals;
private CalculatorChangeListener listener;
public CalculatorData() { this.clear(); }
public void addChangeListener(final CalculatorChangeListener listener) { this.listener = listener; }
public void clear() {
this.display = "0"; this.buffer = 0.0;
this.initDisplay = true; this.lastOpEquals = false;
if (listener != null) listener.onChange(this);
}
public double getBuffer() { return buffer; }
public void setBuffer(double buffer) { this.buffer = buffer; listener.onChange(this); }
public String getDisplay() { return display; }
public void setDisplay(String display) { this.display = display; listener.onChange(this); }
44. ButtonDigit is extension of the GWT Button class and includes a
CalculatorController object reference in its constructor
It invokes the controller’s processDigit() method each time a
ButtonDigit instance is clicked, achieved via a ClickListener.
public class ButtonDigit extends Button {
public ButtonDigit(final CalculatorController controller,
final String label) {
super(label);
this.addClickListener(new ClickListener() {
public void onClick(Widget sender) { controller.processDigit(label);
}
});
this.setStyleName(CalculatorConstants.STYLE_BUTTON_DIGIT);
}
}
45. ButtonOperator has a model, represented by the label; a
view, managed by the parent class of Button, and a controller layer
represented by an AbstractOperator instance, which translates actions
up to the larger scope controller for the calculator widget.
public class ButtonOperator extends Button {
public ButtonOperator(final CalculatorController controller,
final AbstractOperator op) {
super(op.label);
this.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
controller.processOperator(op); }
});
this.setStyleName(CalculatorConstants.STYLE_BUTTON_OPERATOR);
}
}
46. The controller handles the interaction between
various components.
The controller is called upon by the various
components (buttons) to perform actions such
as invoking an operation or manipulating the
model or internal state.
GWT allows to create custome UI and classes for
any logic and data representations, which end
up in the client browser as completely non-
view-related items.
47. public class CalculatorController {
CalculatorData data;
AbstractOperator lastOperator;
Private double prevBuffer;
public CalculatorController(final CalculatorData data) { this.data = data; }
public void processClear() { data.clear(); lastOperator = null; }
public void processEquals() { … } // set display data to CalculatorData Buffer
public void processOperator(final AbstractOperator op) {
if (op instanceof BinaryOperator) {
if ((lastOperator == null) || (data.isLastOpEquals())) {
data.setBuffer(Double.parseDouble(data.getDisplay()));
data.setInitDisplay(true);
} else { lastOperator.operate(data); }
lastOperator = op;
} else if (op instanceof UnaryOperator) { op.operate(data); }
data.setLastOpEquals(false); }
public void processDigit(final String s) { … } // operation when digit button is clicked
}
48.
49. CSS and other resources can be defined and injected through
GWT module configuration (i.e. Calculator.gwt.xml module file).
<stylesheet src='com. gwtip.calculator.style.css'/>
The public path defaults to the public subdirectory of the source
tree, and resources are copied to output folder of the project
when compiled and deployed.
The setStyleName() (addStyleName()) method is used to connect
a style name to a UI component.
Also a limited individual style attributes can be set using methods
like setVisible(), setHeight(), and setWidth().
Invoke com.google.gwt.dev.GWTShell with the following
command-line options, to force the GWT shell to delay startup
until a debugger has connected:
-Xdebug -Xnoagent -Djava.compiler=NONE -
Xrunjdwp:transport=dt_socket,server=y,address=8888,suspend=y
50. GWT enables client applications to communicate with
server resources through its own RPC and object-
serialization mechanism.
The communication process involves implementation
of GWT service interface and sending/receiving special
GWT serialized data.
GWT optimizes the translation of data from Java to
JavaScript and vice versa during communication.
The native mechanism for GWT client-server
communication is GWT RPC, but it also supports plain
XML over HTTP (POX), or JSON.
51. The GWT ProjectCreator utility is used to make
Eclipse project files.
ProjectCreator [-ant projectName] [-eclipse
projectName] [-out dir] [-overwrite] [-ignore]
Parameter Description
-ant Generates an Ant build file to compile source (.ant.xml will be
appended).
-eclipse Generates an Eclipse project.
-out The directory to which output files will be written (defaults to the
current directory).
-overwrite Overwrites any existing files.
-ignore Ignores any existing files; does not overwrite them.
52. The Data class must be marked with either the
com.google.gwt.user.client.rpc.IsSerializable or the
java.io.Serializable interface.
GWT honors the transient modifier on class
properties, allowing them to be omitted if they are
not themselves serializable.
IsSerializable implementations should declare a no-
arguments constructor.
In GWT1.4, the Java serialization protocol is
explicitly not supported.
Both IsSerializable or Serializable can be used
synonymously.