Category Archives: GWT/ JSNI / COMPILER

GWT Compiler – Compiling for one browser and also supporting hosted mode

When you want to compile your GWT module for only specific browser, you can change  UserAgent.gwt.xml inside gwt-user.jar in package

Find this text and change it as you wish:
<define-property name=”user.agent” values=”ie6,gecko,gecko1_8,safari,opera”>

gecko – Mozilla ,gecko1_8  –  FireFox

I want to compile for only IE , then I change it into

<define-property name=”user.agent” values=”ie6″>

I want to do this because we limit specification of browser for our application, and by doing this we can get more space up to 40%

GWT spends time to compute permutations : create javascript file per browser/locale. With this kind of application, GWT produces 50 permutations :

  • 5 browsers : ie6, opera, gecko1_8, safari, gecko
  • 10 locales : default, de_DE, en_UK, fr_FR, hr_HR, hu_HU, it_IT, nl_NL, pl_PL, pt_PT


1) Force a single browser

You can add the following set-property in ModuleName.gwt.xml

<!– User Agent –>

<set-property name=”user.agent” value=”xxxx” />
where value = “ie6/opera/gecko1_8/safari/gecko”

Note: Add only one User Agent set-property in your ModuleName.gwt.xml

For example in MODULE com\mymodule\Container.gwt.xml:
<module >
<!– Inherit the core Web Toolkit stuff. –>
<inherits name=””/>
<!– Inherit the GWT-EXT stuff. –>
<inherits name=”com.gwtext.GwtExt” />
<!– Inherit the GWT-EXT User Extension stuff. –>
<inherits name=”com.gwtextux.GwtExtUx” />
<inherits name=”com.gwtextux.GridSearchPlugin”/>
<!– User Agent –>
<set-property name=”user.agent” value=”ie6″ />
<!– Include the core ExtJs files. –>
<stylesheet src=”js/ext/resources/css/ext-all.css” />
<script src=”js/ext/adapter/ext/ext-base.js” />
<script src=”js/ext/ext-all.js” />
<script src=”js/pagebus/pagebus.js”/>

2) Use only one locale

By default, GWT uses “default” locale. So no need to worry about the locale settings.

By doing this you can see the files difference in MODULENAME/html/*.* (If you are using Cypal Studio)  MODULENAME/www/*.* (If you are using GWT Designer) before and after added the set-property in ModuleName.gwt.xml

With this two points, GWT really speeds up we can get more space up to 30% to 40% and compilation timewill be almost 40% less.

Compile GWT files more than one browser

If  you add user.agent=ie6 the compiled code will work only in IE6.

If  you add the following user.agent then your code will work both the browsers (IE6 & Firefox 2/3)

<!– User Agent –>

<set-property name=”user.agent” value=”ie6″/>

<set-property name=”user.agent” value=”gecko1_8″/ >

If you add  <set-property name=”user.agent” value=”ie6,gecko1_8″/>

you will get an error message like below

[ERROR] Invalid property value ‘ie6,gecko1_8′
[ERROR] Failure while parsing XML

More info

Javascript Debug Toolkit – Debug javascript in ie,firefox,chrome,safari,opera and all browsers support ajaxToo


Posted by on November 10, 2008 in GWT/ JSNI / COMPILER


Tags: , ,

GWT 1.6 – Tomcat or Jetty ?

Bruce Johnson (tech lead of the Google Web Toolkit ) is asking the community if it would rather have Jetty or Tomcat as the hosted mode embedded HTTP. Unfortunately, I do not know Jetty enough to have an opinion. But if you know both Jetty and Tomcat, you should not hesitate to participate in this debate.

The GWT team has started putting together a 1.6 roadmap, which we’ll publish as soon as we have it nailed down. Two of the areas we want to work on for 1.6 are some improvements to hosted mode startup time and a friendlier output directory structure (something that looks more .war-like).

As part of this effort, we’ve all but decided to switch the hosted mode embedded HTTP server from Tomcat to Jetty. Would this break you? (And if so, how mad would you be if we did it anyway?)


Tags: , ,

GUID – Globally Unique Identifiers

What is an GUID / UUID ?

A UUID (or GUID) is a unique identifier that can be created whithout a central authority. UUIDs can be used if a sequence number is not good enough. This implementation is thread safe and very fast.

UUID generates version 1 UUIDs that contain the the MAC address of a network card. To obtain it, the following commands are invoked and their respective output parsed:

What is it used for?

UUIDs are applied for identification purposes in a number of fields in the computer industry.

Possible uses are (but are not limited to):

  • The identifiers in the windows registry.
  • Identifiers used in databases.
  • Identifiers used in RPC (COM, CORBA) (remote procedure calls)

To ensure nobody else would – by accident – provide something conflicting.

What does it look like?

The formal definition of the UUID string representation is  provided by the following :

UUIDs are basically 128 bit numbers, normally presented in the following hexadecimal – grouped form:


UUID = time-low “-” time-mid “-” time-high-and-version “-” clock-seq-and-reserved clock-seq-low “-” node

time-low = 4hexOctet

time-mid = 2hexOctet

time-high-and-version = 2hexOctet

clock-seq-and-reserved = hexOctet

clock-seq-low = hexOctet

node = 6hexOctet

hexOctet = hexDigit hexDigit

hexDigit = “0” / “1” / “2” / “3” / “4” / “5” / “6” / “7” / “8” / “9” / “a” / “b” / “c” / “d” / “e” / “f” / “A” / “B” / “C” / “D” / “E” / “F”

In Microsoft Windows, run–> CMD–> ipconfig /all


1 Comment

Posted by on October 12, 2008 in GWT/ JSNI / COMPILER


Tags: , , ,

More on GWT Web Mode files

Before reading this article please have a look Google Web ToolKit – Hosted Mode Vs. Web Mode

Create a SampleGWT application and run in web mode, we need to do the following:

  • Compile the SampleGWT application first, by running the SampleGWT-compile script.
  • The above step will create a www folder in the SampleGWTdirectory. Navigate to the www/com.sample.gwtworks.SampleGWT.SampleGWT directory.
  • Open the SampleGWT.html file in your web browser.

Everything needed to run the SampleGWT client application is contained in the www folder. You can deploy the contents of the folder to any servlet container and serve up the SampleGWT application. Here are the contents of the folder after completing the above steps:

SampleGWT.html: The host page that functions as the main HTML page for the SampleGWT application.

gwt.js: A generated JavaScript file that contains bootstrap code for loading and initializing the GWT framework.

History.html: An HTML file that provides history management support.

xxx-cache.html and xxx-cache.xml: One HTML and XML file per supported browser are generated. These contain the JavaScript code generated by the compilation of the source Java files in the com.sample.gwtworks.SampleGWT.client and com.sample.gwtworks.SampleGWT.server packages. For instance, in this case, on Windows, the compilation produced these files shown in below image . Each set of HTML and XML files represents one supported browser:

The file names are created by generating Globally Unique Identifiers (GUIDs) and using the GUID as part of the name. These file names will be different on different computers, and will also be different every time you do a clean recompile of the application on your computer. There is also a master HTML file generated (com.sample.gwtworks.SampleGWT.SampleGWT.nocache.html) that selects the right HTML file from the above files and loads it, depending on the browser that is running the application.

The www folder does not contain the code from the com.sample.gwtworks.SampleGWT.server package. This server code needs to be compiled and deployed in a servlet container so that the client application can communicate with the random quote service. In normal development mode, we will use the hosted mode for testing, which runs the server code inside the embedded Tomcat servlet container in the GWT development shell. This makes it very easy to run and debug the server code from inside the same Eclipse environment as the client application code. This is another feature of GWT, which makes it an extremely productive environment for developing AJAX applications.

In the web mode, our client Java code has been compiled into JavaScript unlike in the hosted mode. Also, you will notice that the SampleGWT.gwt.xml is not in this directory. The configuration details from this module are included in the generated HTML and XML files above.

Thankfully, all this work is automatically done for us by the GWT framework when we run the SampleGWT-compile script. We can focus on the functionality provided by our AJAX applications and leave the browser-independent code generation and lower level XmlHttpRequest API to GWT.

More in Hosted Mode

You can also compile the SampleGWT application from the GWT development shell in hosted mode. Run the SampleGWT-shell command script to run the application in hosted mode. Click on the Compile/Browse button in the GWT development shell window. This will compile the application and launch the application in a separate web-browser window.

All this dynamic JavaScript magic means that when you try to view the source for the application from the web browser, you will always see the HTML from the host page. This can be disconcerting when you are trying to debug problems. But the fantastic Eclipse support in GWT means that you can debug issues from the comfort of a graphical debugger by setting breakpoints and stepping through the entire application one line at a time.

1 Comment

Posted by on October 12, 2008 in GWT/ JSNI / COMPILER


Tags: , , , ,

Google Web Toolkit – Hosted vs. Web Mode

What is Hosted Mode and Web Mode ?

When you invoked a GWT application you were using what Google calls hosted mode. Hosted mode is only used during development. When in production, your application will be running in web mode. Before going any further in using GWT you need to understand the difference between the two. Note that as of this writing, hosted mode is only available on Windows and Linux.

Hosted mode

Think of hosted mode as training wheels for your GWT application. It’s a hybrid development environment unique to GWT that lets your code run as real Java code, but still inside a browser. Execution in hosted mode is controlled by the Google Web Toolkit development shell.

The development shell is actually an Eclipse Rich Client application, consisting of the shell console, a tomcat server, and one or more hosted browsers.

The hosted browser has two connections back to the development shell. One is just a regular http connection to get the web pages, .css files, images, and other resources. All these are handled by the embedded Tomcat server using a servlet called

The second connection is a back-door that intercepts all interactions inside the hosted browser and routes them not to JavaScript but to Java code in the shell. That Java code in turn calls your real client Java code, which was compiled to bytecode by your IDE. The exact details of how this is done are hidden in the shell code, which is not open source.

  • The Shell program opens a hosted browser window, which loads MyApp.html.
  • MyApp.html loads gwt.js with a <script> tag.
  • gwt.js scans MyApp.html and parses out the <meta name=’gwtmodule’> to get the module name.
  • GWT reads the module file (MyApp.gwt.xml) to find the name of the EntryPoint class (MyApp).
  • The MyApp class is instantiated and its onModuleLoad( ) method is called. Your application begins.
  • Your application code makes calls into the GWT user library (gwt-user.jar), which is also Java code.
  • Code in gwt-user.jar manipulates the hosted browser’s DOM to add UI components to the web page, and redirects all browser events back to the Java application code using special hooks in the browser.

Because real Java code is running, you can use Java tools like the Eclipse debugger, findbugs, pmd, JUnit, and so forth. It’s almost as if you were developing a rich client program with Swing or SWT because it’s Java end-to-end.

Once you’ve debugged and unit tested your code the next step is to compile it into a form that can be run inside a regular browser (not one that has been hijacked by the development shell). That’s where web mode comes in.

Web mode

When you click the Compile/Browse button in the hosted browser, the GWT compiler translates your .client package into JavaScript and opens a normal web browser to view the application. At this point pages are still served by the shell’s Tomcat instance, but they could just as easily come from the file system or a normal web server.

Another way to invoke the GWT compiler is with the shell script provided by the scaffolding (MyApp-compile). You could also write an Ant script to do it if you prefer. For example to maintain the gwtpowered site I have an ant script that does the compile and then copies everything to my hosting provider. You can find the source at

However you invoke it, the GWT compiler combines your code with a JavaScript version of the GWT API (the equivalent of gwt-user.jar) in one JavaScript file. This code and several supporting files are placed in the www directory inside your project. Everything from your public directory is copied there as well. The table below explains what all the files do:

Filename ———————-Description
long-hex-name.cache.html ———–Compiled JavaScript
long-hex-name.cache.xml  ———–Implementation defined
module-name.nocache.html———–Cache file selection
gwt.js —————————-Common GWT bootstrap code
history.html ———————–Contents of history IFrame
MyApp.html ———————–Main page, copied from public
tree*.gif ————————–+/- images used by the Tree widget

(more on GWT Web Mode Files)

The flow of execution during a page load in web mode is a bit different than in hosted mode.
Here’s a breakdown of what happens:

  1. The web browser loads MyApp.html.
  2. MyApp.html loads gwt.js with a <script> tag.
  3. gwt.js scans MyApp.html and parses out the <meta name=’gwtmodule’> to get the module name.
  4. gwt.js modifies the page to include an <iframe> that causes the source file module-name.nocache.html to be loaded.
  5. JavaScript inside the file module-name.nocache.html looks at the browser’s userAgent field to determine what kind of browser the user is running (IE6, Mozilla, Opera, etc.). Then it selects the correct code (cache file) for that browser type and redirects the <iframe> there.
  6. The JavaScript equivalent of your onModuleLoad( ) method is executed, and the rest of your application goes from there.  Manipulations to the browser DOM are performed with ordinary dynamic HTML calls in the compiled JavaScript.


By default, the GWT Java to JavaScript compiler will produce obfuscated output. Code that has been obfuscated is smaller than humanreadable code, and is harder to reverse-engineer. It’s very difficult to debug, though. Should you ever need to debug the JavaScript that GWT produces, you can turn off obfuscation with command line parameters on the GWT compiler (for example as arguments to the MyApp-compile.cmd script). Use the -style pretty option to produce good looking output with readable names and indentation. To see full Java types as part of the names, use the -style detailed option instead.


Posted by on October 7, 2008 in GWT/ JSNI / COMPILER


Tags: , , , , , , , , , , , , , ,

Javascript Native Interface – JSNI


Sometimes when you’re writing Java code (especially if you’re doing systems programming) you find that you have to get closer to the metal and run code outside the Java virtual machine. For example, you might need to access a code library that’s in a different language. To do that in Java, you would declare a method as native and then provide the implementation of that method in another language, such as C. This is called the Java Native Interface (JNI). You can do the same thing with GWT Java code on the client, except instead of C code, the native language for the browser is JavaScript. That’s how Google came up with the name JavaScript Native Interface (JSNI).

Declaring a Native Method

To declare a native method in JSNI, use Java’s standard native keyword just like you would with JNI. In JNI, the native C code is in a separate file, compiled separately and dynamically loaded at run time. In JSNI, the native JavaScript code is embedded directly in your Java source in a specially formatted comment:

public class Alert {
public static native void alert(String msg)


A JSNI comment block begins with /*-{ and ends with }-*/.

As this example shows, when accessing the browser’s window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and
$wnd and $doc are automatically initialized to correctly refer to the host page’s window and document instead of the frame.

How it Works
In Web mode, the GWT compiler converts the client half of your Java program into JavaScript. So normally, when the compiler sees a method declaration, code inside the braces has to go through some kind of translation process. If it’s a native method, however, the compiler’s job is easier. All it has to do is copy the JavaScript native code directly into the compiled result.

If you’ve used Microsoft’s Visual C++ or the GNU C++ compiler, the effect is much like inline assembler code, except with a much higher level language than assembler. Since JavaScript is interpreted, any errors in the JavaScript code won’t be evident until run-time.

Calling JSNI from Java
Calling a JSNI method from Java1 is no different than calling a regular Java method. Here’s an example:

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

The caller can’t really tell if the method is native or not. This gives you some flexibility in changing your mind later about how the method is implemented.

Calling Java from JSNI

Going the other way is a little trickier. For example, suppose you pass an object to a JSNI method and you need to access a field or call a method in that object. You’ll need to know how the GWT compiler mangles the Java field and method names so you can access them from your own JavaScript code.

Accessing Java fields

Object Oriented purists would say that you shouldn’t access fields of a Java class directly because it makes it harder to change the implementation of that class later. But hey, we’re writing native code here so we can cut a few corners. The syntax for accessing a Java field is:


obj is the object instance being referenced. For static variables, leave off the instance expression and the trailing period.
class is the fully-qualified name of the class in which the field is declared (or a subclass thereof).
field is the name of the field being accessed.

Invoking Java methods

Calling methods uses a syntax similar to accessing fields, except you must also supply the signature of the method you’re calling. The reason for that is that Java methods can be overloaded, i.e., two methods can have the same name but take different parameters.

The syntax is:


obj is the object instance being referenced. For static methods,
omit the instance expression and the trailing period.
class is the fully-qualified name of the class in which the method is declared (or a subclass thereof).
method is the name of the method being called.
sig is the internal Java method signature (see Section 7.4, Method signatures ).
args is the actual argument list passed to the method.

Method signatures
JSNI method signatures are exactly the same as JNI method signatures except that the method return type is left off. That’s because it’s not needed to figure out which overloaded method you’re referring
to. The following table shows these type signatures:

For example, the Java method:
long f (int n, String s, int[] arr);

has the following type signature:

We will discuss the specific rules for how values passing in and out of JSNI code must be treated.


This code shows some examples of accessing Java fields and methods from within JSNI. It demonstrates passing numbers, strings, booleans, and Java objects into JavaScript. It also shows how a JavaScript method can make a method call on a Java object that was passed in.

public class J2JS {
/** Pass a Java numeric primitive */
public static void testJ2JSNumeric() {
int x = 42;

* Method jsNumeric.
* @param x int

private static native void jsNumeric(int x) /*-{
$wnd.alert(“x is ” + x);

/** Pass a Java String */
public static void testJ2JSString() {
String s = "my string";

* Method jsString.
* @param s String

private static native void jsString(String s) /*-{
$wnd.alert("s is " + s);

/** Pass a boolean */
public static void testJ2JSBoolean() {
boolean b = true;

* Method jsBoolean.
* @param b boolean

private static native void jsBoolean(boolean b) /*-{
$wnd.alert("b is " + b);

/** Pass an arbitrary Java Object */
public static void testJ2JSObject() {
MyJavaObject obj = new MyJavaObject();

* Method jsObject.
* @param obj MyJavaObject
private static native void jsObject(MyJavaObject obj) /*-{
$wnd.alert("Calling getText(): " + obj.@MyJavaObject::getTextAt(I)(3));


If you look at the source code for GWT you’ll see that much of it is defined in terms of JSNI. Most GWT programmers will never need to define JSNI methods themselves, but it’s nice to know the feature is there if you need it.

Leave a comment

Posted by on October 7, 2008 in GWT/ JSNI / COMPILER


Tags: , ,

JSNI Components

JavaScript Native Interface (JSNI)

JSNI is GWT’s mechanism to allow you as a programmer to embed JavaScript in the Java code. We can’t overemphasize the point that JSNI is almost a last-resort approach. Many issues that look like they need JSNI can be solved at the GWT Java level if you spend time looking. It’s possible to view the relationship between GWT Java and JSNI as you do the relationship between a high-level programming language and assembly code: Yes, you can do it, but it’s sensible only if there is a clear need to do so.

It’s possible to carry this analogy further, because JSNI, just like assembly language, is less portable across systems. If you write something in JSNI that works in one browser, there is a risk that it may not work at all, or perhaps may work in a different way, in other browsers. As an example, you can count the number of children for a DOM element using the simple Java GWT DOM.countChildren() method. If you were to write that method in JavaScript, you would have to, as GWT does for you, write several versions to cope with DOM differences between Internet Explorer and the other browsers (check out the DOMImplStandard and DOMImplIE6 classes in the GWT gwt-user.jar file to see the GWT definitions for this method in the different browsers). In JSNI, you can write only one of these methods, or you would have to add the own browser detection JavaScript as well. This isn’t in the spirit of GWT, which advocates writing once and running in many different browsers. There is also the risk that writing your own JSNI code could introduce memory leaks, unless you’re an expert at those matters.

  • NOTE JSNI is applicable only to client-side aspects of your application, because JavaScript doesn’t run on the server side. It’s therefore not possible to use JSNI code in any server-side code or to pass an object over remote procedure calling (RPC) to the server and expect to be able to execute any included JSNI code server-side.

However, let’s be a little more positive about JSNI. In the cases where you do have to use it, it can be powerful. JSNI lets you interface between Java and JavaScript in a type-safe way; you can use JavaScript objects in the Java code and rely on Java’s strong typing to protect you against various programming errors. But again, the more functionality you include in a single JSNI block, the less you can rely on Java’s strong typing to minimize errors.

JSNI also provides a seamless way of moving between Java and JavaScript, allowing you to pass objects and exceptions across the boundary in both directions. Through JSNI, you manage JavaScript objects from Java, and you can call back to the Java code from the JavaScript code you write. One use is to wrap a third-party JavaScript library, where you create JavaScript objects from the library and pass them around the GWT Java code before perhaps sending them back to the JavaScript library. One word of warning about JSNI: It’s potentially a moving target during the early stages of GWT adoption. The existing model works well in most cases, as you’ll see later in this chapter, but already several requests for reviews have been published about changing functionality of certain aspects. A guiding principle of JSNI coding is to spend as little time as possible in “the dark side”; each JSNI method should be at an atomic level (perform one clear function) so that you isolate issues and keep as much control as possible in the strongly-types Java realm. Let’s move on and assume that you’re in a situation where JSNI is the approach you need. The first thing you need to understand is how to use the syntax.

Understanding JSNI

If you’re familiar with writing native methods in Java for other languages, then JSNI will seem relatively familiar. If you’ve never written native methods before, don’t worry; their syntax is a little strange but not frightening. Java Native Interface (JNI) is the Java approach that allows Java code to interface with components written in other languages, for example C or C++ or assembly. JSNI is the GWT Java equivalent for interfacing with JavaScript components, and it follows a syntax similar to that of JNI.

In the next few sections, we’ll look at the syntax used to cross the boundary both ways between Java and JavaScript and how the objects you pass over that boundary are treated. Here’s a simple JSNI method call:

public static native void method_name(ObjectTyp someData)
someData.@org.gwtbook.client.Data::data1 == "GWT In Action"

We hope that doesn’t look too scary, even with the @ and :: symbols sprinkled in. To start to understand why these are there, we’ll first look at how you call Java-Script functionality from a GWT Java program.

Crossing the boundary from Java to JavaScript

To include JavaScript code in a GWT application, you must write it in a specific way so that both the syntax checkers of Java and the GWT Java compiler can recognize it and deal with it appropriately. For syntax checkers, that means ignoring the code because it isn’t Java; and for the GWT compiler, it means merging it in a structured way into the JavaScript output of compilation.

A basic JSNI method is defined as shown here:

In the template, you define the method in a normal Java way, but you must include the keyword native as one of the modifiers (1); this identifies the code to the Java compiler as JNI code and to the GWT compiler as JSNI code. To help any syntax checkers know that they should avoid parsing the JavaScript code, you wrap it as a comment by using a modified standard comment, which starts with the characters /*- (a forward slash, an asterisk, and a dash) and ends with -*/ (a dash, an asterisk, and a forward slash) (2). It’s also important not to forget the trailing semicolon at the end of the definition; otherwise your code won’t compile!

Crossing the boundary from Java to JavaScript can come in two forms: writing JavaScript code in the Java application that performs some dedicated functionality, or writing JavaScript in the Java application that calls functionality in a Java- Script library already loaded into the web browser. Both methods follow the same syntax of extending the previous template to provide parameters, a return type if necessary (otherwise the return type must be defined as void), and the native code. You can consider this crossing of the boundary diagrammatically as shown in figure-1

Figure – 1 The interaction between Java and JavaScript code when crossing the Java-to-JavaScript boundary in a JSNI call from a GWT application

Here is some typical code required to cross the boundary from Java to JavaScript:

Overall, the definition is the same as a normal Java method; you provide a list of parameters that can be passed in and a possible return object type. If you provide a return type, rather than just a void, then the JavaScript must return an object of the correct type. (Be aware that JSNI code can’t create new Java objects; it can manipulate ones passed in or create new JavaScript objects, but not new Java objects.)

  • REMEMBER It isn’t possible to create new Java objects in a JSNI code block. Return types must either be primitive types, manipulated Java objects that have been passed in as input parameters, or references to newly created Java- Script objects (a JavaScriptObject type).

It’s important to understand how the objects you provide as parameters are handled across the Java-to-JavaScript boundary, as you’ll see in the next section.

Passing Java objects across the Java-to-JavaScript boundary

We have mentioned before that one of the benefits of using Java to develop the Ajax/rich Internet applications is the strong typing provided by the Java language, which isn’t present in JavaScript. This missing typing model could cause problems as you start crossing the boundary from Java to JavaScript.
Unfortunately, there isn’t much you can do about the typing capabilities of JavaScript. Once the objects have passed into the realm of JavaScript, they’re sadly on their own. This brings us back to the point we mentioned earlier—the shorter amount of time you can spend in this potentially lawless world of JavaScript, the better. If you have to spend a long time there, it’s preferable that you do so only to interact with stable third-party JavaScript libraries. What you can do, though, is ensure that a clearly defined and repeatable mapping exists between Java typed objects and JavaScript untyped objects, which is what GWT provides.

Primitive Java numeric types, such as byte, short, char, int, long, float, or double, become simple objects in JavaScript whose value is that of the original object. For example, if you have a Java char, char keyPress = ‘a’, then it will become the JavaScript variable var k = ‘a’. Similarly, the Java int, int val = 10, becomes the JavaScript variable var v = 10.

A Java String is translated across into JavaScript as a simple variable to which the original text is assigned. Therefore the Java object String name = “GWT In Action” becomes the JavaScript variable var s = “GWT In Action”. Finally the simple Java boolean, becomes another simple JavaScript variable; the Java boolean b = true becomes the JavaScript variable var b = true.

Moving on to more complicated Java objects that can be passed across the boundary, you have the Java array, a Java object, and a new object to GWT called the JavaScriptObject. We’ll discuss the last object more in the next section; for now, you should think of it as just a reference to a JavaScript object created somewhere else that can be passed around the Java code and on to other JavaScript methods—but you can’t look into its contents from the GWT Java code. This may sound strange, but we’ll explain in more detail later in the section on this object.

Passing an array across the Java-to-JavaScript boundary is treated in a similar opaque way; you know you have an array object, but you can’t look into its contents. This means that if the JavaScript code needs to use values in the array, then you should move them out of the array before you cross the boundary: either into separate parameters or into another type of user-defined Java object. You can manage Java objects in JavaScript through the JSNI interface, as we’ll discuss next.

You can also pass your own defined Java objects across the Java-to-JavaScript  boundary; GWT provides a special syntax allowing you to access the fields and methods of that Java object. This will take a little bit of explaining, so please, stick with us.

Let’s say you have an object of type Data, which is defined by the class shown below

Example class that will be accessed through the Java-to-JavaScript boundary

package org.gwtbook.client;
public class Data{
String data1 = "GWT In Action";
int version = 1;

You use an instance of this type in a new class defined called DataManip

Example class demonstrating accessing Java objects through the Java-to-JavaScript boundary

In the DataManip class, you have a couple of additional class variables: one called correct (1)and then other a static variable called checked (2)(it doesn’t matter what they stand for in this example). You also define a JSNI method (3) called doSomething(), which takes as a parameter an instance of the Data class but returns nothing (we’ll cover going across the JavaScript-to-Java boundary in a short while). When doSomething() is called, you want it to look at the DataManip class’ correct value (4); if that is false, then you want to check the static field checked (5). If that too is false, then you confirm whether the Data instance passed in as a parameter has its data1 field set to “GWT In Action” and the version value set to 1 (6); if they are, then you do something else in the code. To perform this functionality, you need to access an instance field, a static
field, and a field in a Java object passed in as a parameter, in that order. In each case, you need to use the JSNI-specific syntax for accessing Java objects, the template for which is shown in figure – 2

Figure – 2 Explanation of the JSNI method to access a field in a Java object. The first part comprises the name of the instance (an object name, the keyword this, or blank for a static field). Next are the fully
qualified class name and the field name.

When you access the instance field (4), the name of the instance is this, the class name of this instance is org.gwtbook.client.DataManip, and the field you’re after is called correct. Accessing this field is, therefore, performed by writing the following in the JSNI code:


Accessing the static field (5) requires you to access a field where there is no defined objectName (because the field is static across all instances). In JSNI, you write


(Notice that the period is missing and only the @ symbol is still required if there is no object name to reference.)

Finally, when you want to reference the data1 field in the parameter that you’ve passed in, then the parameter name, someData, is the objectName, and you write


You can also access the methods from the Java object passed across the boundary in a similar way. We’ll discuss how that works once you’ve seen how you return objects back across the boundary to the Java code.

Sending objects back across the JavaScript to Java boundary

When you’ve completed the functionality you need in JSNI, it’s common to pass an object back in return. As with all Java methods, you need to define the return type of the JSNI method, which will either be a Java primitive, a Java object, a GWT JavaScriptObject, or void. Diagrammatically, you’re performing the action shown in figure -3 ; once complete, program control is back in the hands of the GWT Java code.

Just as there was a defined mapping between Java and JavaScript objects for the parameters, such a mapping exists when going from JavaScript to Java for the return values.

To get a Java primitive numeric coming out of the method call, the value returned from the JavaScript must be a numeric value. You need to be careful with returning primitive numerics because GWT doesn’t determine whether the type is correct. If you define the Java method to return a Java int, and the Java-Script returns the value 1.5, then the result passed out of that surrounding Java method will be unpredictable.

Returning Strings and booleans is much simpler because they translate directly to their Java equivalents. Java objects can also be returned from the Java-Script; however, you can’t just create Java objects in the JavaScript. If you want to return a Java object, then it must have been passed in as one of the parameters.

Figure – 3
Examining the interaction between Java and JavaScript code when returning values across the JavaScript-to-Java boundary in a JSNI call from a GWT application

Take care if you’re returning null objects, because the JavaScript undefined value isn’t treated by JSNI as null; if it’s used, unpredictable results can occur (you must always use the null value). You may even want to ensure that any JavaScript variable you pass back is checked to be sure it isn’t the undefined value before it’s returned.

We mentioned briefly when passing in parameters that GWT provides a special object called the JavaScriptObject. This type of object can be returned by the JSNI method if a new JavaScript object is created as part of the call. You’ll see this in use often later in this chapter when you use JSNI methods to create new Java-Script objects from a third-party library. You need a reference to these third-party objects in the Java code because you’ll later be calling methods on them, and they’re therefore passed back as subclasses to the JavaScriptObject. This Java-ScriptObject is opaque to the Java code—you can’t use Java code to call the methods in it or even to see its fields; you need to pass them back into new JSNI methods to do that. But you’ll see this in action a little later. First we need to finish our journey through the JSNI syntax by looking at how you can call Java methods
from JavaScript.

Crossing the boundary from JavaScript to Java

As well as being able to access fields on Java objects from JavaScript, you can execute methods defined in those objects in a similar manner, as shown in figure – 4

Figure 4 Examining the interaction between JavaScript and a Java object when crossing the JavaScript to Java boundary in JSNI

To refer to a method, you use a syntax similar to that you used to refer to fields. There are, however, some slight differences. This time, the generic template for calls to methods is shown in figure  – 5

The first part of this should be familiar from when you were accessing fields, with the same discussion about there being no objectName if you’re accessing a static method, using this if you accessing a method in the current instance, and using the parameter name if you’re accessing a passed-in object to a method. The difference occurs in the second half of the template, where you see the values param-signature and arguments. The arguments part is a list of the various arguments whose types match the parameter signature. JSNI uses the internal Java

Figure 5Explanation of the JSNI method to access a method in a Java object. First is the
instance name, followed by the fully qualified class name. The method name is followed by the
parameter signature and then the arguments.

method signature to define the parameter signature, but it doesn’t require a definition of the return type to be included. Parameter type signatures are defined in  below table.

Java type signature for various Java types

Let’s look at a simple example

Sample attempts to call methods in a Java class from JavaScript

In (1), you call the m1() method in this class, which takes a Java String as its parameter; so, you must define the parameter signature as Ljava/lang/String;. Then, you call the m2() method (2), which expects an integer, so the method signature is I. (In your code, these definitions should all be on one line—it’s sometimes difficult to get all of them on one line in the book!) The final type of objects that can come out of the JSNI call are exceptions.

Handling exceptions

It’s strongly recommended that JavaScript exceptions be handled in the Java-Script segments of the JSNI method and that Java methods be handled in Java code. The reason is that when a JavaScript exception creeps over the JavaScript boundary into the Java, it becomes, and can only become, an object of type

You don’t necessarily lose information about the JavaScript exception, because you can use the getName() and getDescription() methods to return String values about the original JavaScript exception. But relying on these methods leads to messy code requiring the use of String comparison to handle the exceptions, whereas they can be handled more gracefully in the JavaScript code. The only exception to this rule is where an exception is raised in Java code called by a JSNI method, which is then handed back to more Java code. In this case, the original Java exception typing is preserved through the boundaries.
With all these basics in place, let’s look at the occasions when we said you may need to use JSNI, starting with how you perform different types of communication between components (browser, GWT applications, and legacy code).


JSNI is an extremely powerful way of interfacing with existing JavaScript libraries and filling in the gaps where GWT may not yet have the functionality you need. It allows you to apply some of the good control and typing aspects of Java to the Java-Script interfaces; however, you should keep your use of JavaScript to a minimum. View using JSNI as you would writing assembly-language code segments in a highlevel language project—it’s for specialized tasks, not for everyday use. The main reason for restricting the use of JavaScript is cross-browser issues, just as assemblylanguage coding restricts your ability to move projects to other machines.

If you’re going to use JSNI, remember that it’s valid only in your client-side components, and you’ll need to use the $wnd and $doc variables instead of the standard JavaScript window and document variables because of the way GWT loads your application. Also remember that when you’re executing JavaScript code, you don’t have the protection of GWT when it comes to browser differences (for example, the JavaScript getElementById() method isn’t as robust as the GWT’s cross-browser DOM.getElementByID() method). Finally, GWT and JSNI don’t allow you to get around any normal restrictions of JavaScript coding; for example, you  still can’t subvert the security mechanisms that browsers employ.

We’ve reached the end of our journey through the more client-side related aspects of GWT, and it’s time to consider the flexibility that GWT provides when building a real-sized application—using GWT’s modularization aspects.

Leave a comment

Posted by on October 6, 2008 in GWT/ JSNI / COMPILER


Tags: , , , , ,

%d bloggers like this: