Google Web Toolkit (GWT) – Create Ajax applications in Java: Examples and Concepts

24 July, 2008 at 20:00 10 comments

GWT imageGoogle Web Toolkit (GWT) is an open source Java software development framework that allows web developers to create Ajax applications in Java. It is licensed under the Apache License version 2.0.

GWT emphasizes reusable, efficient solutions to recurring Ajax challenges, namely asynchronous remote procedure calls, history management, bookmarking, and cross-browser portability.

Google Web Toolkit (GWT) is an open source Java development framework that lets you escape the matrix of technologies that make writing AJAX applications so difficult and error prone. With GWT, you can develop and debug AJAX applications in the Java language using the Java development tools of your choice. When you deploy your application to production, the GWT compiler translates your Java application to browser-compliant JavaScript and HTML.

Here’s the GWT development cycle:

  1. Use your favorite Java IDE to write and debug an application in the Java language, using as many (or as few) GWT libraries as you find useful.
  2. Use GWT’s Java-to-JavaScript compiler to distill your application into a set of JavaScript and HTML files that you can serve with any web server.
  3. Confirm that your application works in each browser that you want to support, which usually takes no additional work.

Google Web Toolkit Features

  • Dynamic, reusable UI components Create a Widget by compositing other Widgets. Lay out Widgets automatically in Panels. Send your Widget to other developers in a JAR file.
  • Really simple RPC To communicate from your web application to your web server, you just need to define serializable Java classes for your request and response. In production, GWT automatically serializes the request and deserializes the response from the server. GWT’s RPC mechanism can even handle polymorphic class hierarchies, and you can throw exceptions across the wire.
  • Browser history management No, AJAX applications don’t need to break the browser’s back button. GWT lets you make your site more usable by easily adding state to the browser’s back button history.
  • Real debugging In production, your code is compiled to JavaScript, but at development time it runs in the Java virtual machine. That means when your code performs an action like handling a mouse event, you get full-featured Java debugging, with exceptions and the advanced debugging features of IDEs like Eclipse.
  • Browser compatible Your GWT applications automatically support IE, Firefox, Mozilla, Safari, and Opera with no browser detection or special-casing within your code in most cases.
  • JUnit integration GWT’s direct integration with JUnit lets you unit test both in a debugger and in a browser…and you can even unit test asynchronous RPCs.
  • Internationalization Easily create efficient internationalized applications and libraries.
  • Interoperability and fine-grained control If GWT’s class library doesn’t meet your needs, you can mix handwritten JavaScript in your Java source code using our JavaScript Native Interface (JSNI).
  • Google API Library: Google Gears support We are in the process of building support for using Google APIs in GWT applications. Initially, we are providing support for Google Gears, the recently-launched developer product that extends the browser to allow developers to make web-based applications function even while offline. If you would like to download this library please visit the open source project. We are planning to add support for other Google APIs; if you’d like to help, please check out Making GWT Better.
  • Completely Open Source All of the code for GWT is available under the Apache 2.0 license. If you are interested in contributing, please visit Making GWT Better.

Why GWT?

The Google Web Toolkit (GWT) provides a significant boost to Ajax development. Any new technology like this is a hard sell especially when there are many other choices. In reality, nothing gives you the benefits GWT gives you for Ajax applications. If you’re not already bound to a framework it just doesn’t make sense to not use it. By using GWT for your Ajax application you get big performance gains for free. (more)

Fast, Easy, Beautiful: GWT – Presentation

Web services and GWT

There are a lot of new and interesting web services popping up on the web these days, and you may want to make use them in your GWT applications. In this short guide, I will show you how to call these public apis from within your GWT app. The main difficulty when trying to talk to some web service on another server is getting past your web browser’s Same-Origin Policy. This basically says that you may only make calls to the same domain as the page you are on. This is good for security reasons, but inconvenient for you as a developer as it eliminates the use of GWT’s HTTP library functions to achieve what we want to do. One way to get around this is to call a web service through a javascript tag which bypasses this problem. In his book, Google Web Toolkit Applications, Ryan Dewsbury actually explains this technique in more detail and provides a class called JSONRequest which handles all the hard work for us. JSON is one of the more popular data formats, so most web services support it. Lets leverage Ryan’s code and take a quick look at how it works.

public class JSONRequest {
  public static void get(String url, JSONRequestHandler handler) {
    String callbackName = "JSONCallback"+handler.hashCode();
    get( url+callbackName, callbackName, handler );
  }
  public static void get(String url, String callbackName, JSONRequestHandler handler ) {
    createCallbackFunction( handler, callbackName );
    addScript(url);
  }
  public static native void addScript(String url) /*-{
    var scr = document.createElement("script");
    scr.setAttribute("language", "JavaScript");
    scr.setAttribute("src", url);
    document.getElementsByTagName("body")[0].appendChild(scr);
  }-*/;
  private native static void createCallbackFunction( JSONRequestHandler obj, String callbackName)/*-{
    tmpcallback = function(j) {
      obj.@com.gwtsite.client.util.JSONRequestHandler::onRequestComplete(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
    };
    eval( "window." + callbackName + "=tmpcallback" );
  }-*/;
}

(more)

Creating Custom Widgets

GWT makes it easy to create custom widgets entirely in the Java language.

Composites

Composites are by far the most effective way to create new widgets. You can easily combine groups of existing widgets into a composite that is itself a reusable widget. Composite is a specialized widget that can contain another component (typically, a panel) but behaves as if it were its contained widget. Using Composite is preferable to attempting to create complex widgets by subclassing Panel because a composite usually wants to control which methods are publicly accessible without exposing those methods that it would inherit from its panel superclass. This is an example of how to create a composite.

From Scratch in Java code

It is also possible to create a widget from scratch, although it is trickier since you have to write code at a lower level. Many of the basic widgets are written this way, such as Button and TextBox. Please refer to the implementations of these widgets to understand how to create your own.

Using JavaScript

When implementing a custom widget that derives directly from the Widget base class, you may also write some of the widget’s methods using JavaScript. This should generally be done only as a last resort, as it becomes necessary to consider the cross-browser implications of the native methods that you write, and also becomes more difficult to debug. For an example of this pattern in practice, see the TextBox widget and its underlying implementation.

GWT Examples

Demonstrate Scriptaculous effects

This is a very simple example using the Google Web Toolkit along with Robert Hanson’s GWT Widget Library to demonstrate Scriptaculous effects. Click an icon to see the effect. Hover over an icon to view any effect options (if any). All descriptions were taken from the Scriptaculous wiki. Source code: EffectsDemo.java | EffectPanel.java More

Alert based on a meta property

What this example will do is alert a message to the screen based on a meta property set in the html page. Here are the steps:

1. I am going to create java classes that will alert a message to the
screen. Each one of these classes will implement an Alerter
interface:

package com.zedak.alerter.gwt.client.impl;
...

public interface Alerter {
public void alert();
}

2. Here are my implementations of the above Alerter interface:

package com.zedak.alerter.gwt.client.impl;
...

public class HelloAlerterImpl implements Alerter{
public void alert() {
Window.alert(“Hello!”);
}
}

public class GoodbyeAlerterImpl implements Alerter{
public void alert() {
Window.alert(“Goodbye!”);
}
}

public class DefaultAlerterImpl implements Alerter{
public void alert() {
Window.alert(“Default!”);
}
}

3. I am going to create a property which will be utilized by GWT to
determine which implementation my Alerter will use. I am going to
define my properties in a seperate XML file than my main module to
reduce clutter…

Contents of Alerter-properties.gwt.xml:

<module>
<define-property name="alerter" values="hello,goodbye,default" /

<property-provider name=”alerter”>
<![CDATA[
var alerter = __gwt_getMetaProperty(“alerter”);
if (alerter == null){
alerter = “default”;
}
return alerter;
]]>
</property-provider>
</module>
The HTML will contain a meta property that will define which alerter
to use. If no meta property exists, it will use the default.

4. I now will inherit the above module in my main module and define
which Alerter implementation to use for each possible property.

Contents of Alerter.gwt.xml:

<module>
....

<!– Inherit the above module –>
<inherits name=”com.zedak.alerter.gwt.Alerter-properties” />

<replace-with
class=”com.zedak.alerter.gwt.client.impl.HelloAlerterImpl”>
<when-type-is
class=”com.zedak.alerter.gwt.client.impl.AlerterImpl”/>
<when-property-is name=”alerter” value=”hello”/>
</replace-with>

<replace-with
class=”com.zedak.alerter.gwt.client.impl.GoodbyeAlerterImpl”>
<when-type-is
class=”com.zedak.alerter.gwt.client.impl.AlerterImpl”/>
<when-property-is name=”alerter” value=”goodbye”/>
</replace-with>

<replace-with
class=”com.zedak.alerter.gwt.client.impl.DefaultAlerterImpl”>
<when-type-is
class=”com.zedak.alerter.gwt.client.impl.AlerterImpl”/>
<when-property-is name=”alerter” value=”default”/>
</replace-with>

<entry-point class=’com.zedak.alerter.gwt.client.AlerterEntryPoint’/


</module>
5. Now lets create the EntryPoint class defined in the above XML,
which will call the Alerter implementation based on the property
value…

package com.zedak.alerter.gwt.client;

public class AlerterEntryPoint implements EntryPoint {
public void onModuleLoad() {
Alerter alerter = (Alerter) GWT.create(Alerter.class);
alerter.alert();
}
}

All this module will do is instantiate the appropriate Alerter and
alert the message to the screen. You must use the GWT.create method
to instatiate the Alerter class.

6. Finally, lets add the appropriate code to our Alerter.html page…

<html>
<head>
<meta name='gwt:module' content='js/
gwt=com.zedak.alerter.gwt.Alerter'/>
<meta name='gwt:property' content='alerter=hello'/>
</head>
<body>
<script language="javascript" src="/js/gwt/
com.zedak.alerter.gwt.Alerter.nocache.js"/>
</body>
</html>

When you load the Alerter.html file, you should see an alert dialog that states ‘hello’. If you switch the property to this… <meta name='gwt:property' content='alerter=goodbye'/>
You should see an alert dialog that states ‘goodbye’. Removing the property entirely should display an alert dialog that states ‘default’. I thought a super-simple example might be helpful for some people out there, and I hope that it is.

GWT Ant example

Due to popular demand, I’ve packed a small example distribution together for GWT Ant and XDoclet. Download it, unpack it, and run ant. It’s also an Eclipse project, so you can import it directly in Eclipse. (more)

GWT Hello world example

[wikipedia.org]

[http://code.google.com]

[http://roberthanson.blogspot.com/]

[http://www.gwtsite.com]

[http://www.ongwt.com/]

[http://braindump.dk] Bookmark and Share

Advertisements

Entry filed under: Ajax, GWT, Java, JavaScript. Tags: , , , .

JRuby – Java and Ruby: Concepts, Methods and Examples REST (Representational State Transfer) and RESTful web services: Methods, Concepts and Examples

10 Comments Add your own

  • 1. anonymous  |  26 July, 2008 at 08:09

    I found this blog on a google search and boy am I glad I did. I thought I heard someone mention it in a free chat room.
    Awesome read!

    Reply
  • 2. Maurizio Storani  |  26 July, 2008 at 12:16

    Thanks so much

    My pleasure

    🙂

    Reply
  • 3. Koonal  |  1 February, 2009 at 08:55

    Hi, zat article is really nice and it help a lot to understand.
    Btw my project would seek to build a GWT Widget that would send/receive messages from a Jade agent.
    Can u help????

    Reply
  • 4. John  |  21 March, 2010 at 15:45

    Super post. The section “Alert based on a meta property” is enormously helpful!

    Reply
  • 5. Allan  |  5 March, 2011 at 17:55

    The gift that keeps on giving. I found this via google. Exactly what I want. Thanks!

    Reply
  • 6. proxy uk  |  13 December, 2013 at 22:50

    What’s up everyone, it’s my first go to see at this web site,
    and article is actually fruitful for me, keep up posting these types
    of articles or reviews.

    Reply
  • 7. Lottie  |  11 August, 2014 at 11:13

    This is really fine- Thanks and also carry on the fine creative work!

    Reply
  • 8. Cns Vps  |  13 August, 2014 at 11:11

    This will be genuinely great!! I must acknowledge, If your web page was deemed a person; I may say You are able to probably
    lead
    a rebellion… Thanks plus maintain the good creative
    work!!

    Reply
  • 9. steam shower kits  |  20 August, 2014 at 22:24

    Had been in actual fact searching for just a normal shower enclosures before I stumbled upon this site, did not even know there was such
    a thing as a ‘steam shower enclosure’, incredible, might just have to have
    one

    Reply
  • 10. chojnow  |  19 September, 2014 at 03:53

    Aw, this was an exceptionally good post. Spending some time and actual
    effort to create a top notch article… but what can I
    say… I put things off a whole lot and never manage to get anything done.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


IT Passion’s Store

Archives

Communities

Get the Source
OSGi supporter
JUG Milano

Upcoming Events



....

Blog Stats

  • 328,400 hits

My PageRank

What's My Google PageRank?

%d bloggers like this: