GWT Development AJAX Application Tutorial

Source: Internet
Author: User
Tags add date define object string version tostring stringbuffer
first, the introduction

If you are a Java software and Ajax developer, then Google Web Toolkit (GWT) should have caught your eye.

Google has released this free development kit under the Apache License agreement in May 2006. GWT was designed to simplify the development of AJAX applications in the Java language. The beta version of Google's initial release can be applied to Windows and Linux platforms and promises to release a version of Mac OS X later.

This article explores the complete process of using GWT and familiar Java tools on Mac OS X, such as the Apache Ant,tomcat 5.0 servlet container and the IntelliJ idea integrated development environment to develop a simple AJAX application.

Note This article assumes that the reader has a certain base of Java and Ant usage.

   second, use Ant with gWT

I downloaded the GWT Linux beta version and chose the Java Development application, then compiled with an ant build file, and finally published the application on a Tomcat 5.0 instance. Note that this ant file is running the GWT java-to-javascript compiler. In fact, this "compiler" is just a command-line script that executes a GWT Java class that is responsible for writing JavaScript for the application.

Using GWT Beta includes two development methods: Host mode and Web mode.

The host approach is to use an embedded GWT browser and intermediate development steps; In this way, your compiled code continues to run in a Java Virtual machine (JVM). However, the host approach cannot be applied to our Mac OS X users who use the Linux version of the operating system. Only if Google releases a version of Mac OS X can we use the host method.

   three, different styles of web development

While creating a remote procedure call (RPC) service, this article discusses in detail some of the web development-related tasks that typical GWT developers might face. RPC is part of a software model designed primarily for applications that use service-oriented architecture (SOA). These development tasks include:

· Automate the development and release steps with a build file (build and run the GWT compiler, then publish the compiler's output, and publish your server-side Java class files to a servlet container, such as tomcat,jetty or resin).

· Use Firefox's DOM inspector to observe the HTML generated by the GWT application.

· Reset the parts on the page without having to access the inner HTML (since you're using GWT's Java API).

· Make sure that HTML is a valid tag, for example, your organization may need to be based on a particular XHTML document type.

   Four, the service function

First, I'll briefly describe the service that this sample application is creating, and design This example to show the model that GWT uses.

The application displays a form in the browser that asks the user to enter their name, age, and country of origin. When the user submits the form by clicking the button, the application displays a server response in a text field without initializing a page refresh. Figure 1 shows what the application looks like in the Safari browser.


Figure 1. A simple view generated by GWT

For example, when a user keeps a text box blank and clicks the Ok,submit button, the result shown in Figure 2 is displayed.


Figure 2: The application displays an error message in red

   v. The ingenious service mechanism

Using RPC in an AJAX application eliminates the need to explicitly handle XMLHttpRequest and associated server return values because GWT objects can handle complex tasks for you.

Each service defined by your application requires the implementation of two Java interfaces and a Java class. To compile these classes, you must ensure that the Gwt-user.jar library is located in your classpath (which is responsible for implementing this task by an ant file portal). The following code example shows the Java interface that defines our service.

Package com.parkerriver.gwt.testapp.client;
Import Com.google.gwt.user.client.rpc.RemoteService;
Public interface Showrespservice extends remoteservice{
String Displayresponse (string req);
}

This service interface requires extended GWT interface Remoteservice. It defines a single method Displayresponse ().

In addition, you must define a client (or use the final downloaded JavaScript code) to invoke this service method's interface. When I display the client code (refer to Myform.java), the GWT uses a callback design pattern that I describe.

Package com.parkerriver.gwt.testapp.client;
Import Com.google.gwt.user.client.rpc.AsyncCallback;
Public interface Showrespserviceasync {
public void Displayresponse (String s,asynccallback callback);
}

This AsyncCallback object is responsible (as part of the GWT API) for client-side processing of service responses.

   六、一个 servlet

Finally, you must define a Java class that implements the remote service interface. This class will be located on the server side of your AJAX application.

Package com.parkerriver.gwt.testapp.server;
Import Com.parkerriver.gwt.testapp.client.ShowRespService;
Import Com.google.gwt.user.server.rpc.RemoteServiceServlet;
Import Java.util.Date;
public class Showrespserviceimpl extends Remoteserviceservlet
Implements Showrespservice {
public string Displayresponse (string req) {
if (Req.length () 1) {
throw New IllegalArgumentException (
"Blank submissions from the client are invalid.");
}
StringBuffer buf = new StringBuffer ("Your submission:");
Date date = new Date ();
String ServerInfo = This.getservletcontext (). Getserverinfo ();
Buf.append (req);
Buf.append ("\ n");
Buf.append ("Server response:");
Buf.append (Date.tostring ());
Buf.append ("\ n");
Buf.append (ServerInfo);
return buf.tostring ();
}
}

This class must inherit Remoteserviceservlet (this is a GWT API object that itself inherits from Javax.servlet.http.HttpServlet). In other words, this class and its implementation interfaces must be published in your servlet container.

   Vii. Steps

Now that you have defined the service, let's review the directory structure of the application. GWT includes a command-line scripting Applicationcreator, which enables you to generate a framework for your engineering directory structure. After you unzip the downloaded GWT, you will find the Applicationcreator in the top-level directory. I start with the following command line:

Applicationcreator-out/users/bruceperry/1gwt/secondapp/com.parkerriver.gwt.testapp.client.myform

Figure 3 shows what the directory looks like.


Figure 3: A GWT and IntelliJ engineering directory

Applicationcreator generates./SRC directories and Myform-compile and Myform-shell scripts. My ant file executes myform-compile; another script will start the host mode in GWT mode. this./SRC directory contains nested directories to match your package name, as shown in Figure 4.


Figure 4. Java packages and modules for a GWT application

The MyForm.gwt.xml file is a generated configuration file, which is actually a "module" of the GWT call. It specifies the Java class that describes your application's "entry point" (This is a Java class that resembles a main () method).




The!--specifies the application entry point class. -->


Other files or directories, including./classes,./web-inf and./GWTPROJ.IPR, are necessary components of a IntelliJ WEB application project; Therefore, you do not have to pay special attention to them.

Also, the./www directory does not appear until you generate the GWT compiler for your application code (unless you create it yourself). My project uses the ant file Gwtproj.xml, as well as the properties defined in Gwtproj.properties. Before I show you the ant build file, let's take a look at the Myform.java class that describes the application entry point.

   Eight, the entry point

This Myform.java class implements the GWT API interface EntryPoint, so the class must implement the Onmoduleload () method, which is invoked by the browser's JavaScript engine when the browser loads your AJAX application.

In other words, the GWT compiler compiles this class into JavaScript code. The Myform.java class creates a form widget for the browser view. The class also determines the user's response when clicking OK and the Submit button. The comments in the code are described in detail, so there is no longer much to say here.

Note that most of the code in this class is dealing with the GWT API. Interestingly, if you have to implement JavaScript DOM programming (as shown in the Showrpcstatus () method), you can use Java to implement the Com.google.gwt.user.client.DOM class.

   ix. Building Documents

The following are the main features of the ant build file:

1. Compile the Java files into the./classes Directory of the engineering directory.

2. Perform the GWT compilation script (in this case, myform-compile).

3. Move the resulting code generated in the./www directory to a larger Web application that has been published to Tomcat.

4. Copy the compiled Java servlet and related interfaces (Showrespservice) to the same Web application.

Note that the two goals here: compiling Java classes and initializing the transformations to JavaScript may fail the entire build process if any errors occur during the period.

   10. Ant XML

The following is what the Gwtpoj.properties file contains (omitting other content):

Web.deploy.location=/users/bruceperry/parkerriver/gwt
Web.classes.location=/users/bruceperry/parkerriver/web-inf/classes

The following XML describes the main features of the ant file just now:



Location of the top-level directory and ant file for the


!--directory in the top-level directory./classes-->
"${module.gwtproj.basedir}/classes"/>

!--this target call Myform-compile to create all content under the./www Directory-->
"Compile.production.classes"
description= "Use GWT ' s compiler" >



"${module.gwtproj.basedir}/myform-compile"
Failonerror= "true"/>

"${module.gwtproj.basedir}/www" >



"Compile the Gwtproj production classes"

"On" failonerror= "true" nowarn=
"Off" memorymaximumsize= "128m" fork=
"True" executable= "${module.jdk.home.gwtproj}/bin/javac" >





!--copy Java servlet classes to a Web application-->
description= "Copy classes to Web directory" > >






description= "Build All"/>

You can run this ant file from within the IDE (in IntelliJ) or in the directory containing the build file by using the following command line:

Ant-buildfile Gwtproj.xml

In most cases, after modifying the application and running ant, you can see the changes in the browser by overloading the browser page.

   11, installation

Note that when installing, you must add the Gwt-user.jar library to the/web-inf/lib directory of your WEB application.

I added the jar file created and the Javax package (Gwt-user-deploy.jar) to the/web-inf/lib directory. This is because Tomcat does not load a single Web application's library file if it already contains the Servlet API class.

   12, difficult

Applicationcreator will also create an HTML front-end for your AJAX application, in this case myform.html.

What if your application's HTM must meet a standard (such as XHTML transitional or strict)? For XHTML Transitional, I first add the required DOCTYPE to the top of myform.html and the associated properties of the HTML tag:

! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"Http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd" >

I then uploaded myform.html to the WWW Association's HTM verifier (located in http://validator.w3.org/).

After running the validator, I have slightly modified the HTML, such as properly closing the META tag and adding a type= "text/javascript" to the script tag.

However, if you want to meet XHTML strict standards, more complex modifications are required. For example, the authentication program for the consortium will display the IFRAME tag as "undefined element", which is required by GWT's historical support feature, which provides the same functionality as a browser back button. The IFRAME element has been removed from the XHTML strict.

This may not be a problem for you (it may be addressed in a future version of GWT, and there are any other obvious problems), but you can also implement other optional strategies, such as extending GWT's classes and creating your own compatible widgets.

   13, Position alignment problem

A common problem in web development is the visual design of applications. The designer of the project might want to make the page look like it was created in Adobe Illustrator, right?

Although you may not be able to achieve this ideal visual effect when you develop a complex AJAX project, you can at least use Firefox's Dom inspector to observe the HTML that your Java class eventually generates. Then, modify it from here.

For example, go to Firefox's "Tools=>dom Inspector" menu item (see Figure 5).


Figure 5: Using DOM Inspector to observe the background implementation content.

The image above shows that the Com.google.gwt.user.client.ui.Grid object you use in Java code is implemented as an HTML table tag. The TD tag that contains the Ok,submit button in this table is associated with a style property whose value is "Verticle-align:top".

The following are the Java code associated with the initialization of the appropriate format in the Myform.java class:

Set the vertical position of the OK button cell
Grid.getcellformatter (). Setverticalalignment (3,0,
Hasverticalalignment.align_top);

If you do not make this call in your code, the button may float up and down in the middle part of the text field.

   14, Summary

Google Web Toolkit (GWT), published by the company, has aroused widespread concern in the industry. Since GWT is designed to simplify the development of AJAX applications in the Java language, Ajax is the technical foundation of the Web 2.0 era, so the buzz from GWT releases should be expected.

This article only gives examples of using GWT and familiar Java tools to develop a simple AJAX application, and more research on GWT is just beginning and relies on the efforts of a broad readership.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.