Build an Ajax-enabled application using the Google Web ...

destructivebewInternet and Web Development

Jul 19, 2012 (5 years and 1 month ago)

564 views

Build an Ajax-enabled application using the Google
Web Toolkit and Apache Geronimo,Part 1:Run
compiled Google Web Toolkit applications on
Geronimo
Skill Level:Intermediate
Michael Galpin
Developer
Adomo,Inc.
08 May 2007
Asynchronous Java™Script + XML (Ajax)-enabled Web applications have taken the
software development world by storm.Some of the most notable ones have been
built by Google.This two-part tutorial series shows you how the Google Web Toolkit
(GWT) and Apache Geronimo can help you rapidly build sophisticated Ajax Web
applications—without having to write any JavaServer Pages (JSP) components,
servlets,or JavaScript.
Section 1.Before you start
This tutorial,the first in a two-part series,is for Java developers who want to create
Ajax-enabled Web applications and learn about the GWT and Apache Geronimo.
About this series
Ajax-enabled Web applications have become incredibly popular recently.Ajax
makes Web applications behave a lot like desktop applications.They offer greater
interactivity and functionality than the previous generation of Web applications.And
Geronimo provides the perfect platform for building Ajax-enabled Web applications.
However,building Ajax-enabled Web applications is more difficult than building
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 1 of 36
traditional Web applications.It involves lots of JavaScript and Dynamic HTML
(DHTML) development.Quirks among different browsers—and even different
versions of the same browser—further complicate things.The GWT is one of many
Ajax frameworks that makes your job easier by using a novel approach that lets you
write all of your code in the Java language and generates all the JavaScript for you.
The two tutorials in this series cover the following topics:
• Part 1 focuses on getting started with GWT and creating a simple
Ajax-enabled Web application for retrieving stock quotes.
• Part 2 shows you how to make the stock quotes application more
sophisticated and how to transform it into a stock portfolio application,
leveraging both GWT and Geronimo.
About this tutorial
Check out the Ajax Resource Center,your one-stop shop for
information on the Ajax programming model,including articles and
tutorials,discussion forums,blogs,wikis,events,and news.If it's
happening,it's covered here.
In this tutorial,you build an Ajax-enabled Web application using the GWT and find
out how easy it is to develop GWT applications and deploy them using Geronimo.
This tutorial covers:
• Installing GWT.
• Using GWT's command-line tools.
• Programmatic UI development using GWT's widgets.
• Creating an Ajax-enabled service called by your Web application.
• Building and deploying the application using Geronimo.
Prerequisites
This tutorial is about building a Java Web application,but you'll only need to
understand the basics of Java servlets.GWT leverages many ideas common to
other technologies,such as layout management,event systems,and remote
procedural calls (RPCs),so prior exposure to these ideas makes it easy to master
GWT.You'll also work with the Geronimo Console,HTML,and cascading style
sheets (CSS),so some familiarity with these tools is helpful.
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 2 of 36
System requirements
You need the following software to set up your development environment before
getting started:
• Geronimo 2.0 with Tomcat — The sample Web application in this tutorial
was built using Geronimo with Tomcat,but it should also work with
Geronimo with Jetty,because everything is standard Java Platform,
Enterprise Edition (Java EE).This tutorial uses Geronimo 2.0 (M3) but
should work with older versions of Geronimo as well.
• Java 5 or Java 6 — The sample Web application uses generics and
annotations.It was developed using Java 6,but also tested against Java
5.
• Apache Jakarta implementation of JSTL 1.1 — Geronimo 1.1 is a certified
J2EE 1.4 implementation,so you need to use JSTL 1.1.
• Google Web Toolkit — This tutorial is all about the GWT;download GWT
1.3.3 for this tutorial.
• Eclipse — The sample Web application is built using Eclipse,as you'll see
from the screen captures.GWT includes a convenient command-line tool
for creating a skeleton Eclipse project.It's not hard to build GWT
applications without Eclipse,but Eclipse provides a great debugger to
debug your GWT application.
Install GWT
To get started with GWT,you first need to install it.When you go to the GWT
download page,it presents you with a GWT distribution that is specific to your
operating system.That's because GWT includes several command-line executables
for generating artifacts needed for your application.Some of the artifacts that it
creates include executables for running the GWT Java-to-JavaScript compiler and
for running your application in hosted mode.
After you've downloaded GWT,extract it and navigate to the directory where you
extracted it.You should see files similar to those in Figure 1.
Figure 1.GWT installation directory
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 3 of 36
Notice the executable files,such as applicationCreator.cmd and projectCreator.cmd.
You use these to generate your application and an Eclipse project for your
application.You might also want to create an environment variable — GWT_HOME
for example.The tutorial refers to this variable.
That's all there is to installing GWT!No installers to run or anything like that.Just
extract the archive,and you're ready to start building a Web application using GWT.
Section 2.Build a stock quote application
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 4 of 36
In this tutorial,you're going to build a Web application that looks up the information
on a stock.A user inputs the symbol for a stock,and the application retrieves
information about the stock.You'll use Yahoo's quote service to look up this
information,because it's free to use and easy to work with.
If you were building this as a traditional Web application,you'd create and submit a
form.Submitting the form would trigger the server to invoke business logic (in this
case,looking up the stock information from Yahoo.) But here you're going to use
Ajax,so you won't have a form at all.The request information (the stock symbol,in
this case) is sent asynchronously to the server where the business logic is invoked.
Your server then returns the stock information.The information is consumed by a
JavaScript callback method that manipulates the Web page's Document Object
Model (DOM) to dynamically create the HTML elements to display the stock
information.Sounds complicated,right?Not with GWT!
One of the many great features of GWT is that it provides easy-to-use command-line
tools to jumpstart application development.You'll use these tools to set up your
application and create an Eclipse project for your application.
Let's get started.
The applicationCreator
Open a command prompt in $GWT_HOME,and enter the command
applicationCreator -out <directory for code>
org.developerworks.stocks.client.StocksApplication,substituting the
path to the directory that you want to use for your code.Executing this command
creates all the directories and associated skeleton files for you,as shown in Listing
1.
Listing 1.Creating the application
C:\code\gwt-windows-1.3.3>applicationCreator -out
c:\code\stocks
org.developerworks.stocks.client.StocksApplication
Created directory c:\code\stocks\src
Created directory
c:\code\stocks\src\org\developerworks\stocks
Created directory
c:\code\stocks\src\org\developerworks\stocks\client
Created directory
c:\code\stocks\src\org\developerworks\stocks\public
Created file
c:\code\stocks\src\org\developerworks\stocks\StocksApplication.gwt.xml
Created file
c:\code\stocks\src\org\developerworks\stocks\public\StocksApplication.html
Created file
c:\code\stocks\src\org\developerworks\stocks\client\StocksApplication.java
Created file c:\code\stocks\StocksApplication-shell.cmd
Created file c:\code\stocks\StocksApplication-compile.cmd
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 5 of 36
There are several things you should notice here:
• You put your application,
org.developerworks.stocks.client.StocksApplication,into
the client package—a recommended practice for GWT—while services
should be in a server package.Everything in the client package is
compiled to both Java code and JavaScript,whereas everything in the
server package is only compiled into Java bytecode.
• The public directory is useful for HTML files.You only need HTML files
with GWT,no JSPs or JavaServer Faces (JSFs)—though it's possible to
use these as well.
• There were two executable files created:StocksApplication-shell
and StocksApplication-compile.The compile executable file
causes GWT to compile your Java code in the client package to be
compiled into JavaScript.The shell application launches GWT's
embedded Web server (Tomcat) so you can run your application in
hosted mode.You'll see this in action later.
Now that you've set up your application,you can get it ready to use with Eclipse.
The projectCreator
Now it's time to create an Eclipse project.Enter the command projectCreator
-eclipse stocks -out <path to source code>,as shown in Listing 2.
Listing 2.Creating an Eclipse project
C:\code\gwt-windows-1.3.3>projectCreator -eclipse stocks
-out c:\code\stocks
Created directory c:\code\stocks\test
Created file c:\code\stocks\.project
Created file c:\code\stocks\.classpath
The projectCreator created the.project and.classpath files for your Eclipse
project,and even created a test directory for unit tests.Now you just need to import
your new project into Eclipse.
Import your project into Eclipse
1.Open Eclipse,and select File > Import,as shown in Figure 2.
Figure 2.Import project into Eclipse
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 6 of 36
2.Select Existing Projects into Workspace,and click Next,as shown in
Figure 3.
Figure 3.Import existing project
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 7 of 36
3.Enter the path to the code created earlier.Eclipse should detect the
project,as shown in Figure 4.
Figure 4.Select project to import
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 8 of 36
4.Click Finish,and the Eclipse Package Explorer should show the project
(see Figure 5).
Figure 5.Project contents
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 9 of 36
Now you've created your basic project.Go ahead and give it a try.Double-click the
StocksApplication-shell executable file,and you should see something like Figure
6.
Figure 6.Default application in hosted mode
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 10 of 36
You haven't written any code yet,but you already have a working application.GWT
took care of a lot of boilerplate code for you.Now you're ready to start coding your
application.
Section 3.Develop the application
Application development should be all about writing the code to implement the
business logic of your application.Unfortunately developers often spend more time
creating the plumbing of the application.GWT does a lot of that for you,so you can
concentrate on writing the logic unique to your application.You've already created a
lot of the basic artifacts that GWT needs to Ajax-enable your application,and you've
set up an Eclipse project for your application.In this section,you concentrate on the
business logic.
The stock service
Now it's time to create your stock service,which retrieves stock information for a
given symbol.You need to create an interface for your service and declare it in the
client package—another important convention in GWT.See the code for your
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 11 of 36
StocksService interface in Listing 3.
Listing 3.StocksService.java
package org.developerworks.stocks.client;
import com.google.gwt.user.client.rpc.RemoteService;
public interface StocksService extends RemoteService {
public Stock getQuote(String symbol);
}
It's a pretty simple interface,but there are a couple of important things to notice.
First,you need to extend the GWT RemoteService interface.This is just a marker
interface that lets GWT know that this will be used for Ajax calls.Next,notice that
your service returns a class called Stock.You need to define that next.
The Stock data structure
The Stock class is a simple data structure for your stock data.Take a look at it in
Listing 4.
Listing 4.Stock.java
package org.developerworks.stocks.client;
import com.google.gwt.user.client.rpc.IsSerializable;
public class Stock implements IsSerializable {
private String symbol;
private String companyName;
private double price;
private double change;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public double getChange() {
return change;
}
public void setChange(double change) {
this.change = change;
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 12 of 36
}
public String toString(){
StringBuffer str = new StringBuffer();
str.append(this.companyName);
str.append(":");
str.append(this.symbol);
str.append("$");
str.append(this.price);
str.append("");
str.append(this.change);
return str.toString();
}
}
This is a pretty typical JavaBeans component.The most important thing to notice is
that it implements the IsSerializable interface,another GWT marker interface.
It's similar to Java's java.io.Serilizable interface,except that
IsSerializable represents an object that can be serialized to JavaScript.So it's
a little stricter than Java's Serializable interface.Now that you've defined your
service interface,you need to implement it.
Implement the stock service
As mentioned earlier,the GWT convention is to put server-side code in the server
package.That's where you'll put the implementation class,shown in Listing 5,of
your service interface.
Listing 5.StocksServiceImpl.java
package org.developerworks.stocks.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.developerworks.stocks.client.Stock;
import org.developerworks.stocks.client.StocksService;
import com.google.gwt.user.client.rpc.InvocationException;
import
com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class StocksServiceImpl extends
RemoteServiceServlet implements StocksService {
private static final String YAHOO_QUOTE_URL =
"http://quote.yahoo.com/d/quotes.csv?s=:symbol&f=sl1d1t1c1ohgvj1pp2owern&e=.csv";
public Stock getQuote(String symbol) {
String urlStr =
YAHOO_QUOTE_URL.replace(":symbol",symbol);
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 13 of 36
conn.connect();
InputStream is = conn.getInputStream();
InputStreamReader isr = new
InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
Stock stock =new Stock();
while ( (line = br.readLine())!= null){
String[] stockArray = line.split(",");
for (int i=0;i<stockArray.length;i++){
stock.setCompanyName(stockArray[16].replaceAll("\"",""));
stock.setSymbol(stockArray[0].replaceAll("\"",""));
stock.setPrice(new
Double(stockArray[1]));
stock.setChange(new
Double(stockArray[4]));
}
}
return stock;
} catch (MalformedURLException e) {
throw new InvocationException("Something
was wrong with the URL",e);
} catch (IOException e) {
throw new InvocationException("Exception
reading data from Yahoo",e);
}
}
}
There are a couple of things to note here.Most importantly,your class extends the
GWT class RemoteServiceServlet.This causes your implementation class to
become a servlet for handling remote requests.Also,notice that you caught any
exceptions and threw them again as GWT InvocationExceptions.It's important
to throw some kind of exception so that your servlet creates an error response.
Finally,note that even though your service is going to be running as a servlet,you
haven't written any servlet-based code.Do you see any mention of HttpRequest
or HttpResponse in Listing 5?
GWT module declaration
Your service is being deployed as a servlet.You must be thinking,"Don't you need a
URL mapping to this servlet?"You're absolutely right.When you deploy to
Geronimo,you of course need to map a URL to your stocks service servlet.You also
need to let GWT know about this mapping.To do that,you edit the
StocksApplication.gwt.xml file (created by the applicationCreator executable
file earlier) and as shown in Listing 6.
Listing 6.StocksApplication.gwt.xml
<module>
<!-- Inherit the core Web Toolkit stuff.
-->
<inherits name='com.google.gwt.user.User'/>
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 14 of 36
<!-- Specify the app entry point class.
-->
<entry-point
class='org.developerworks.stocks.client.StocksApplication'/>
<servlet path="/stocksService"class=
"org.developerworks.stocks.server.StocksServiceImpl"/>
</module>
The only thing you changed was adding the servlet node.The inherits and
entry-point nodes are boilerplate code provided by the applicationCreator.
The asynchronous version of the stock service interface
There's one last GWT-related action you need to perform to complete your service.
You need an asynchronous version of your service.If you're familiar with RPC-style
programming,this just means you need operations in your interface to have a void
return type.How do you pass back your stock information if there's no return type?
GWT provides a wrapper class for response data called AsyncCallback.
There's one more GWT convention to use here:You name your asynchronous
interface by appending Async to the name of your interface (for example,
StocksServiceAsync).Listing 7 shows the interface declaration.
Listing 7.StocksServiceAsync.java
package org.developerworks.stocks.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface StocksServiceAsync {
public void getQuote(String symbol,AsyncCallback
callback);
}
The interface is similar to your StocksService interface.You don't actually
implement this interface.It's compiled as JavaScript and used as part of the Ajax call
generated by GWT.
The stocks application
Your service is ready to be called,so all you need to do is create your application.
Here,you're going to write the application in the Java language.In many ways,it'll
look like a Swing or Standard Widget Toolkit (SWT) application.That's the idea
behind GWT.Just remember that all of your application code is actually compiled
into JavaScript and deployed to Web browsers.With that being said,take a look at
the application code in Listing 8.
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 15 of 36
Listing 8.StocksApplication.java
package org.developerworks.stocks.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import
com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class StocksApplication implements EntryPoint {
StocksService service;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
//declare the UI elements used in the app
final Button button = new Button("Get Quote");
final Label stockLabel = new Label();
final TextBox textBox = new TextBox();
//get a handle on the async version of our service
final StocksServiceAsync stocksService =
(StocksServiceAsync)
GWT.create(StocksService.class);
ServiceDefTarget endpoint = (ServiceDefTarget)
stocksService;
String moduleRelativeURL = GWT.getModuleBaseURL() +
"stocksService";
endpoint.setServiceEntryPoint(moduleRelativeURL);
//create the response handler
final AsyncCallback callback = new AsyncCallback()
{
public void onFailure(Throwable caught) {
stockLabel.setText("Sorry there was an
error");
}
public void onSuccess(Object result) {
Stock stock = (Stock) result;
stockLabel.setText(stock.toString());
//show things as green or red depending on if the stock
is up or down
if (stock.getChange() > 0){
stockLabel.setStyleName("stockUp");
} else if (stock.getChange() < 0){
stockLabel.setStyleName("stockDown");
}
}
};
//create event listener for the button
button.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
String symbol = textBox.getText();
stocksService.getQuote(symbol,callback);
}
});
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 16 of 36
//make hitting return the same as clicking the button
textBox.addKeyboardListener(new
KeyboardListenerAdapter() {
public void onKeyPress(Widget sender,char
keyCode,int modifiers){
if (keyCode =='\r'){
button.click();
}
}
}
);
//These are the elements that the widgets are being added
to
RootPanel.get("quoteButton").add(button);
RootPanel.get("stockInfo").add(stockLabel);
RootPanel.get("quoteBox").add(textBox);
}
}
Let's go through what is going on in Listing 8.First you declare some UI
elements—a text box,button,and label.The text box is where the user enters the
stock symbol.The button triggers an Ajax call to your service.And the label is used
to show stock information.
Stocks applicationthe widgets
UI elements,like your text box,button,and label,are often referred to in GWT (and
many other UI frameworks) as widgets.GWT comes with an extensive list of
widgets.You've already seen simple ones,like the Button,TextBox,and Label.
There are more complex ones,like MenuBar,Table,and Tree.In GWT there's
also a UI component called a panel,which is a widget that can contain other
widgets.A panel can define a layout algorithm.For example,a HorizontalPanel
lays out a widget from left to right,as the name suggests.
The next four lines of code in Listing 8 create a handle to the asynchronous version
of your service by using the utility library class GWT.The last two lines set up the
URL used to invoke the service.Remember,all this code is going to be compiled
into JavaScript!
The next section of code in Listing 8 creates the handler for the response from your
service.Remember that the response is asynchronous from the request,so you
create a callback method for handling the response.You use an anonymous class
for this.This kind of programming is common to event-driven UI code like Swing and
JavaScript.Again,this code will be compiled into JavaScript where the callback
object will be passed as a functor (or function object) when the Ajax request is sent
to your service.
Stocks applicationthe Ajax call
The actual callback logic is pretty simple.There are methods to the callback:
onFailure and onSuccess.The onFailure says it handled an exception (a
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 17 of 36
throwable) from the service.Of course,this will become a serialized version of any
exception (remember that's why you wanted to make sure to throw any exceptions
when you implemented the service).It will simply display an error message.
The onSuccess method is called when things go as planned.In that case,you
expect a Stock object to be returned.You simply display the info on the stock.
There's one fancy piece of logic in here.You set the style of the information
depending on whether the stock price change was up or down.That's what the
stockLabel.setStyleName() call does.This lets you show the information in
green if the stock had a good day and red information if it went down.
Tie the application and the service together
Next in Listing 8,you add event listeners to your button and your text box.Again,
this is pretty standard for any event-driven UI framework.You use anonymous
classes again,and you use some convenience classes courtesy of GWT.For
example,the ClickListener class allows you to only have to handle the one
event you care about:clicking your button.Similarly,you used the
KeyboardListenerAdapter to catch key press events.You only look for people
hitting the Return button,and then turn this into a button click.
And what does clicking the button do?You simply get the value of the text in the text
box and call your service.Notice how you pass the callback as a parameter to the
service invocation.As mentioned earlier,when this is converted to JavaScript,it
becomes a functor,being passed to the Ajax invocation.
The last section in Listing 8 simply maps the UI components you created (the text
box,button,and label) to elements in your HTML page's DOM.You'll look at that
HTML page shortly.
You've written the application logic.It's all in Java code now,but it will all be in
JavaScript when you run your application.You need to create the view (shown in
Listing 9),which in this case is simply an HTML page.
Listing 9.StocksApplication.html
<html>
<head>
<title>GWT Stocks Application</title>
<style>
#stockInfo{
text-align:center;
padding-top:10px;
}
#quotes{
text-align:center;
}
#quoteBox{
padding-right:5px;
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 18 of 36
}
.stockUp{
color:green;
}
.stockDown{
color:red;
}
</style>
<!--
-->
<!-- The module reference below is the link
-->
<!-- between html and your Web Toolkit module
-->
<!--
-->
<meta name='gwt:module'content=
'org.developerworks.stocks.StocksApplication'>
</head>
<body>
<!--
-->
<!-- This script is required bootstrap stuff.
-->
<!-- You can put it in the HEAD,but startup
-->
<!-- is slightly faster if you include it here.
-->
<!--
-->
<script language="javascript"
src="gwt.js"></script>
<!-- OPTIONAL:include this if you want history
support -->
<iframe id="__gwt_historyFrame"
style="width:0;height:0;border:0"></iframe>
<h1>Stocks Application</h1>
<p>
Enter in the symbol for a stock below.
</p>
<div id="quotes">
<span id="quoteBox"></span>
<span id="quoteButton"></span>
</div>
<div id="stockInfo"/>
</body>
</html>
This is fairly simple.You enter some static text and create the page elements that
you used in your application code to drop in UI components.You have a little CSS
code to lay out your components.You also create the two styles used to make your
stock information either green or red.
Note on browser history
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 19 of 36
One last thing you might notice is the iframe element.This is an optional element
that allows GWT to solve the Back button problem common in Ajax applications.A
traditional Web application has links for going from one page to another.An Ajax
application often accomplishes the same thing without true page links—the links
don't go anywhere.Some JavaScript simply captures that they've been clicked and
makes some kind of asynchronous request to the server.The page is then altered
based on the response from the server.The display changes,just like it would in a
traditional application.In a traditional application,you can use the browser's Back
button to return to the previous page.This doesn't work in an Ajax application,and
some Web sites use some complicated JavaScript to detect that the browser was
clicked and then restore the previous state of the application.
GWT simplifies this greatly.All you have to do is have your application code
implement the HistoryListener interface by implementing its
onHistoryChanged() method.You then register your application with GWT's
History object so you know about the browser history.This allows GWT to handle
the user hitting the Back button.This is one of the most popular features of GWT,
though you won't use it on your application here,because you don't have any links.
Section 4.Run and test the application
Now that you've developed the stocks application,you're probably eager to run the
application and test it.If you're used to doing Web development,this stage of things
usually involves deploying the application to your Web server and running it there.
With GWT you can delay that step until the application is ready to be deployed.You
can run and test without a Web server using GWT's hosted mode.Hosted mode
runs the GWTShell application,a desktop application written using SWT,which is
the same technology used to build Eclipse.Hosted mode uses an embedded version
of Tomcat.
Compile and run in hosted mode
Try out your application.You can simply double-click the StocksApplication-shell
executable file or invoke it from the command line.You should see something similar
to Figure 7.
Figure 7.StocksApplication in hosted mode
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 20 of 36
Notice the URL here:
http://localhost:8888/org.developerworks.stocks.StocksApplication/StocksApplication.html.
This is the URL you need for debugging.Give it a try.Enter a stock symbol.You can
press Enter or click the Get Quote button.Either way you should see something
similar to Figure 8.
Figure 8.Stocks application displaying info
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 21 of 36
If you enter an invalid stock symbol,your service throws an exception when it tries to
parse the results.This gets handled nicely by GWT,as depicted in Figure 9.
Figure 9.Invalid stock symbol throws an exception
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 22 of 36
Click the Compile/Browse button to launch the application in your Web browser,as
shown in Figure 10.
Figure 10.Hosted mode running Web browser
You can test the application more in the browser and even test it in other browsers
to make sure it works properly.Simply use the URL you see in the navigation bar.
Section 5.Build the Web application
You've seen how easy it is to develop an Ajax-enabled application using GWT.Now
it's time to turn this into a Java Web application that you can deploy to Geronimo.All
you need to do is add the basic Web application metadata needed by Geronimo and
package your application as a WAR file.
Create the web.xml
Every Java Web application needs a web.xml file that tells the container how to
deploy the application.The public directory is where you put your HTML,so add a
WEB-INF folder to that directory.That's where you'll put your web.xml file,as shown
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 23 of 36
in Listing 10.
There are a couple of things you should notice in Listing 10.First,you declare your
stocksServiceServlet and then map the/stocksService URL to it.Next,
you set the StocksApplication.html as the welcome page,so all requests are
sent there by default.Your web.xml file conforms to the Java Servlet 2.4 spec.
However,there are a few things you need to add that aren't supported by the Servlet
2.4 spec,so you need a Geronimo deployment plan.
Listing 10.web.xml
<?xml version="1.0"encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>stocksServiceServlet</servlet-name>
<servlet-class>org.developerworks.
stocks.server.StocksServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>stocksServiceServlet</servlet-name>
<url-pattern>/stocksService</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
StocksApplication.html
</welcome-file>
</welcome-file-list>
</web-app>
Create the geronimo-web.xml file
You need to add a geronimo-web.xml file so you can configure the context root of
your application.You put it in the WEB-INF directory with the web.xml file you just
created (see Listing 11).
Listing 11.geronimo-web.xml
<web-app
xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-1.1">
<environment>
<moduleId>
<artifactId>StocksApplication</artifactId>
</moduleId>
</environment>
<context-root>/stocks</context-root>
</web-app>
This is simple.You map/stocks to your application,so http://<domain>/stocks will
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 24 of 36
access your application.You don't have to put/StocksApplication.html there,
because you set that as the welcome-file in web.xml.
Finally,you give your application an artifactId so you can easily identify it when
you use the Geronimo Console.You've created everything you need for your Web
application,now you just need to package it.
Create the WAR file
You could easily create a WAR file by hand,but it's easier and more portable to use
Apache Ant for this.So you'll create an Ant build.xml file (see Listing 12) for your
application.
Listing 12.build.xml
<?xml version="1.0"encoding="utf-8"?>
<project name="StocksGWT"default="all"basedir=".">
<description>
The Stocks GWT build file
</description>
<property name="gwt.module"value="StocksApplication"/>
<property name="GWT_HOME"
value="C:/code/gwt-windows-1.3.3"/>
<property name="app_packge"
value="org.developerworks.stocks"/>
<!-- set classpath -->
<path id="project.class.path">
<pathelement path="${java.class.path}/"/>
<pathelement path="${GWT_HOME}/gwt-user.jar"/>
</path>
<target name="build"description="Compile src to bin">
<mkdir dir="bin"/>
<javac srcdir="src"destdir="bin"includes="**"debug="on"
debuglevel="lines,vars,source"source="1.5">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="jar"depends="build"description="Package up
the
project as a jar">
<mkdir dir="www/${gwt.module}/WEB-INF/lib"/>
<jar destfile="www/${gwt.module}/WEB-INF/lib/stocks.jar">
<fileset dir="bin">
<include name="**/*.class"/>
</fileset>
<fileset dir="src">
<include name="**"/>
</fileset>
</jar>
</target>
<target name="gwt"description="Compiles Java to
JavaScript">
<exec spawn="false"
executable="${gwt.module}-compile.cmd"/>
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 25 of 36
<copy todir="www/${gwt.module}">
<fileset dir="www/${app_packge}.${gwt.module}">
<include name="**"/>
</fileset>
</copy>
</target>
<target name="war"depends="jar,gwt"description="Builds the
war file">
<mkdir dir="www/${gwt.module}/WEB-INF/lib"/>
<copy file="${GWT_HOME}/gwt-servlet.jar"
todir="www/${gwt.module}/WEB-INF/lib"/>
<jar destfile="stocks.war"basedir="www/${gwt.module}"
duplicate="preserve"/>
</target>
<target name="clean">
<!-- Delete the bin directory tree -->
<delete dir="bin"/>
<delete dir="www/${gwt.module}"/>
<delete file="stocks.war"/>
</target>
<target name="all"depends="war"/>
</project>
The build.xml file is pretty typical of a Web application build file.The one unusual
target you might notice is the gwt target.This invokes the GWT compiler that
compiles the Java code in the client package into JavaScript and creates other
artifacts needed by the application.
Now you're ready to use Ant to build your Web application.
Build the WAR file
You can run Ant from inside Eclipse or the command line,since the WAR target is
invoked by default.When you run Ant,you should see output similar to Listing 13.
Listing 13.Ant output
Buildfile:C:\code\stocks\build.xml
build:
jar:
[mkdir] Created dir:
C:\code\stocks\www\StocksApplication\WEB-INF\lib
[jar] Building jar:
C:\code\stocks\www\StocksApplication\WEB-INF\lib\stocks.jar
gwt:
[exec] Output will be written into
C:\code\stocks\www\org.developerworks.stocks.
StocksApplication
[exec] Copying all files found on public path
[exec] Compilation succeeded
[copy] Copying 17 files to
C:\code\stocks\www\StocksApplication
war:
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 26 of 36
[copy] Copying 1 file to
C:\code\stocks\www\StocksApplication\WEB-INF\lib
[jar] Building jar:C:\code\stocks\stocks.war
BUILD SUCCESSFUL
Total time:4 seconds
The Ant output shows that it created the structure for the WAR file and then
packaged all the code and generated code into the WAR file.Take note of the
location of the generated WAR file,because now you're going to deploy it to
Geronimo.
Deploy to Geronimo
You've built your Web application,so now you just need to deploy it to Geronimo:
1.Start Geronimo,and bring up its Console,which is usually found at
http://localhost:8080/console,as shown in Figure 11.
Figure 11.The Geronimo console
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 27 of 36
2.Select Applications > Deploy New,and navigate to the WAR file you
created for your Web application earlier.
3.Click Install,as shown in Figure 12.
Figure 12.Choosing the Stocks WAR file to install to Geronimo
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 28 of 36
4.You should see message indicating that the Web application was
successfully installed and started.Verify this by selecting Applications >
Web App WARs,as shown in Figure 13.
Figure 13.Stock application successfully deployed to Geronimo
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 29 of 36
This brings up a list of installed Web applications on Geronimo.You
should see the stocks application in the list.
5.Click the application's URL to launch it,as shown in Figure 14.
Figure 14.Installed Web apps on Geronimo
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 30 of 36
This should bring up the application in your Web browser,and it should
work just like it did in hosted mode,as seen in Figure 15.
Figure 15.Stocks application running on Geronimo
6.You can load the application in various browsers to confirm that it works
in them.For example,Figure 16 shows it running in the Opera browser.
Figure 16.Stocks application in Opera
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 31 of 36
Your application is now up and running on Geronimo.You've written an
Ajax-enabled Web application without writing any JSPs,servlets,or JavaScript—all
thanks to GWT.
Section 6.Summary
Welcome to Web 2.0 application development!You've created a slick Ajax Web
application by writing Java code.There was a small amount of HTML and CSS,but
mostly lots of Java code.There was no JavaScript code at all.You let the GWT
transform your Java application into an Ajax-enabled Web application.Your
application not only uses Ajax,but you could even call it a mashup,because it
leverages Yahoo's stock quote Web service.Your Ajax application even has
cross-browser support thanks to GWT.
You not only created an Ajax-enabled Web application,you created it using
Geronimo,so it gets all the benefits of any application running inside Geronimo.
Your application only made use of Geronimo's Web container (Tomcat or Jetty).
Geronimo 2.0 is a Java EE 5 application server,so you can use Enterprise
JavaBeans (EJB) 3.0 entity and session beans,messaging,and Web services.
Geronimo also gives you tremendous capabilities on the back end of your
application.Combine these back-end capabilities with GWT on the front end of your
application,and you can rapidly create applications whose powerful features
produce a rich-client interface using Ajax.
In Part 2 of this series,you'll expand on your simple stocks application,making use
of Geronimo's Java EE features,such as EJBs,to persist data.That allows you to
create stock portfolios,not just display simple stock information.You'll also explore
some of GWT's more advanced features,such as JavaScript Native Interface
(JSNI),and see how it lets you embed native JavaScript inside your client Java
code.Stay tuned for Part 2!
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 32 of 36
Downloads
Description
Name
Size
Download
method
Tutorial source code stocks.source.zip 9KB HTTP
Information about download methods
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 33 of 36
Resources
Learn
• The best place for GWT information is straight from the source,at the official
Google Web Toolkit site.
• Read one of the first in-depth tutorials on GWT in the article"Ajax for Java
developers:Exploring the Google Web Toolkit"(developerWorks,June 2006).
• Enjoyed building an Ajax-enabled Web application with GWT?Try out the
four-part developerWorks tutorial series"Build an Ajax application using Google
Web Toolkit,Apache Derby,and Eclipse".
• Get an introduction to building Ajax applications using Java code in the article
"Ajax for Java developers:Build dynamic Java applications"(developerWorks,
September 2005).
• Are you a fan of design patterns?Learn about some of the most useful Ajax
design patterns in the article"Ajax and XML:Five common Ajax patterns"
(developerWorks,March 2007).
• Learn about advanced GWT techniques in the online book Google Web Toolkit
Solutions:Cool & Useful Stuff.
• GWT is a great tool for building an Ajax application with Geronimo,but it's
certainly not the only tool.Build an Ajax application with JavaServer Faces and
Tomahawk in the tutorial"Build Apache Geronimo applications using
JavaServer Faces,Part 3:Add Ajax functionality with Ajax4jsf (developerWorks,
October 2006).
• Read the article"Deploy J2EE applications on Apache Geronimo"
(developerWorks,January 2006).
• Join the Apache Geronimo mailing list.
• Read Aaron Mulder's online book,Apache Geronimo Development and
Deployment,about installing and configuring the Apache Geronimo application
server.
• See the Geronimo wiki for additional Geronimo documentation.
• Check out the developerWorks Apache Geronimo project area for articles,
tutorials,and other resources to help you get started developing with Geronimo
today.
• Find helpful resources for beginners and experienced users at the Get started
now with Apache Geronimo section of developerWorks.
• Check out the IBM® Support for Apache Geronimo offering,which lets you
develop Geronimo applications backed by world-class IBM support.
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 34 of 36
• Visit the developerWorks Open source zone for extensive how-to information,
tools,and project updates to help you develop with open source technologies
and use them with IBM's products.
• Stay current with developerWorks technical events and webcasts.
• Browse all the Apache articles and free Apache tutorials available in the
developerWorks Open source zone.
• Browse for books on these and other technical topics at the Safari bookstore.
• Get an RSS feed for this series.(Find out more about RSS.)
Get products and technologies
• GWT is not the only exciting new open source Java project from Google.Take a
look at Google Guice,a high-performance dependency injection framework.
• Download Apache Ant.
• Download the latest version of Apache Geronimo.
• Download your free copy of IBM WebSphere® Application Server Community
Edition -- a lightweight J2EE application server built on Apache Geronimo open
source technology that is designed to help you accelerate your development
and deployment efforts.
• Innovate your next open source development project with IBM trial software,
available for download or on DVD.
Discuss
• Participate in the discussion forum for this content.
• Learn about and discuss the latest GWT news and its roadmap at the official
GWT blog.
• Discuss the GWT roadmap at the GWT Wiki.
• GWT may come from Google,but it's completely open source.You can
participate in making GWT better.
• Stay up to date on Geronimo developments at the Apache Geronimo blog.
• Get involved in the developerWorks community by participating in
developerWorks blogs.
About the author
Michael Galpin
ibm.com/developerWorks developerWorks®
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 35 of 36
Michael Galpin has been developing Java software professionally since
1998.He holds a degree in mathematics from the California Institute of
Technology and currently works at Adomo,Inc.
Trademarks
IBM,the IBM logo,and WebSphere are registered trademarks of IBM in the United
States,other countries or both.
Java and all Java-based trademarks are trademarks of Sun Microsystems,Inc.,in the
United States,other countries,or both.
developerWorks® ibm.com/developerWorks
Run compiled Google Web Toolkit applications on Geronimo Trademarks
©Copyright IBM Corporation 2007.All rights reserved.Page 36 of 36