Getting started with Google Web Toolkit

Simple Dialog Box Example

Next, try building a simple dialog box that loads from an existing AJAX URL. Out of laziness, make sure you're importing everything from GWT's client package:

import com.google.gwt.user.client.*;

Replace the contents of onModuleLoad with:

openDialogBox();

and then add the function shown in Listing 4.

Listing 4

Add this Function

01         public void openDialogBox() {
02             final DialogBox dialogBox = new DialogBox();
03             dialogBox.setText("This is my simple dialog box");
04             dialogBox.setAnimationEnabled(true);
05                 dialogBox.center();
06         dialogBox.show();
07         }

If you open this in hosted mode, the diaglog box appears when the page opens, which is a nice demo, but it isn't really useful. Instead, you want to be able to call the dialog box from anywhere in the application, and to do this, you need to expose part of the Java application to JavaScript using the JavaScript Native Interface (JSNI).

First, create a function that declares itself "native" and effectively initializes a JavaScript "API," such as the function shown in Listing 5.

Listing 5

Going Native

01         private native void initJavaScriptAPI (MyApp myapp) /*-{
02                 $wnd.openDialog = function () {
03                         myapp.@com.mycompany.client.MyApp::openDialogBox()();
04                 };
05         }-*/;

Finally, in onModuleLoad, replace openDialogBox() with initJavaScriptAPI():

initJavaScriptAPI(this);

If you refresh hosted mode, you'll see nothing because when the app is loaded, it only declares the JS API – a window only opens when the JavaScript function openDialog() is called. To see this work, add the following line inside the <body> in public/MyApp.html:

<a href="javascript:openDialog();">Open my GWT dialog box</a>

Then, refresh hosted mode, click the link, and watch the dialog open. Although this example is basic, it demonstrates something useful: You can now build complex, cross-browser functionality in GWT and call this functionality from your existing JavaScript applications.

Alternatives

An alternative to using GWT is to use one of the available JavaScript frameworks, such as Scriptaculous/prototype, MooTools, jQuery, or Ext JS.

These frameworks are extremely strong and have improved my JavaScript, but they don't do the the same thing as GWT. For specific, smaller (but not small) pieces of AJAX/Web 2.0 functionality, these libraries are great, but after a while, debugging, maintaining, and optimizing in a purely JavaScript environment becomes time consuming.

Using Existing AJAX Apps

The dialog box is still just a nice demo, rather than anything really useful, so spice it up by adding AJAX between an existing AJAX server and GWT.

A typical requirement is for a dialog box to load its contents over AJAX, and you can easily achieve this by modifying your class. Add the code in Listing 6 to the end of openDialogBox().

Listing 6

Adding AJAX

01 RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode("/  AjaxServer.php"));
02
03 try {
04 Request request = builder.sendRequest(null,
05 new RequestCallback() {
06 public void onError(Request request, Throwable exception)
07 // Couldn't connect to server (could be timeout,SOP violation, etc.)
08 dialogBox.setText( "Sorry - Could not load the HTML");
09 }
10
11 public void onResponseReceived(Request request, Response response) {
12 if (200 == response.getStatusCode()) {
13 dialogBox.setText( response.getText() );
14 } else {
15 // Handle the error. Can get the status  text from response.getStatusText()
16 dialogBox.setText( "Sorry - I got the response,  but don't understand it!");
17 }
18 }
19 }
20 );
21 } catch(Exception e) { }

Next, use MyApp-compile to deploy it into an existing application: You'll need some existing web pages running locally – I'll assume you're running a LAMP stack.

Then compile the app and copy the www directory to your existing application:

./MyApp-compile
mv -r www /path/to/my/app/gwt-www
touch /path/to/my/app/gwt-www/AjaxServer.php

Finally, create a file called AjaxServer.php and add the following:

<php
echo "Hello, World from my existing AJAX server called from GWT, but triggered from a native JavaScript call!";
?>

Test the New Feature

To test the new AJAX feature, open up MyApp.htm from inside the application and click the link (Figure 2). The JavaScript API means you can call GWT functionality from the existing JS app, and the use of the AJAX server means that GWT can integrate with your existing AJAX functionality. However, the AJAX URL is hardcoded, so push that URL into a variable passed from JavaScript into Java.

First, modify the contents of initJavaScriptAPI (see Listing 7).

Listing 7

Modifying initJavaScriptAPI

01 $wnd.openDialog = function (url) {
02         myapp.@com.mycompany.client.MyApp::openDialogBox(Ljava/lang/String;)(url);
03 };

The url argument on the first line is a JavaScript parameter, which will be converted to a Java variable of type java.lang.string and passed to openDialogBox.

Then modify openDialogBox to accept the argument

public void openDialogBox(String url) {

and then modify the request to use this variable:

RequestBuilder builder = new RequestBuilder (RequestBuilder.GET, URL.encode( url ));

Now compile it and move the files into your application, then add some URLs to the JS function calls so you can call existing URLs:

<a href=!javascript:openDialog('/AjaxServer1.php');">Open my GWT dialog box</a> <a href="javascript:openDialog('/AjaxServer2.php');">Open another dialog box</a>

In the final step, get the GWT functionality into the web app by including a JavaScript file. Add the script tag to the HTML header, adjusting the src=".." to point to the appropriate directory:

<script type="text/javascript"language="javascript" src="com.mycompany.MyApp.nocache.js"></script>

Then, somewhere in your template, add links that trigger the JavaScript:

<a href="javascript:openDialog('/path/to/ajax.php');">Open my Ajax server</a>

As a test, you could throw this link onto WordPress, your existing CMS, or any other web page.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Google Web Toolkit

    The Ingenious Google Web Toolkit builds optimized JavaScript applications in a hurry.

  • Helma

    The powerful Helma application server brings new powers to the JavaScript language. We'll show you how to use Helma to build a simple RSS reader.

  • AJAX Workshop

    Books were the original model for website design. Navigation was similar to flipping the pages. Thanks to AJAX, many state-of-the-art websites now behave like desktop applications.

  • AJAX

    AJAX offers a fast and efficient approach for building interactive websites. We’ll show you how to call upon the powers of AJAX for your own web creations.

  • Google: A New Crankshaft for V8

    Earlier this week, Google released Crankshaft, a new compilation infrastructure for V8, Chrome's JavaScript engine.

comments powered by Disqus

Direct Download

Read full article as PDF:

072-075_GWT.pdf  (406.51 kB)

News