YOUR FEEDBACK
More on the Software Assembly Question - Do Design Patterns Help?
Yanic wrote: Hi, > UML and MDA are being changed to be more data and doc...


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


AJAX: The Easy Way
With Java and DWR

Digg This!

Page 1 of 2   next page »

Putting AJAX functionality into your Web application can be a daunting task when you're first learning AJAX. After all you're a Java programmer not a JavaScript programmer. It can also be very frustrating having to learn how the different browsers handle XMLHttpRequests. It's been reported, however, that Internet Explorer 7 will support native XMLHttpRequests rather than requiring the developer to make ActiveX requests. This will make a Web developer's life a lot easier.

For Java Developers there are a number of different frameworks/libraries that hide most of the complexity of developing AJAX-enabled Web applications. For this purposes of this article I'll be using one of those libraries called DWR or Direct Web Remoting (http://getahead.itd.uk/dwr/). I chose DWR because I haven't found another framework/library that's easier to use or as flexible.

DWR is an Open Source Java library, distributed under the Apache License version 2, that lets JavaScript call Java methods as if they were running in the browser, when in fact they're running on the server. DWR isn't tied to any one framework so it should work with any standard servlet container.

There are a number of different ways that you can use DWR, and the extensive documentation shows most of them. I've found that having Java methods return the HTML code that I want displayed is the easiest way to learn DWR. Using it this way also allows for the most flexibility in your AJAX designs.

For this article I'll show you how to use DWR to develop two simple AJAX-enabled Web applications. The first Web application will be an old "Hello World" application. This will show just how easy it is to write an AJAX-enabled Web application with DWR. The second application will display the stats of the players on a baseball team. As you select a position, the names of players that can play that position appear in a dropdown select box. Then you can select the player to see their stats.

You'll need to start by downloading the DWR jar file from http://getahead.itd.uk/dwr/ and copy it to the lib directory of your Web application. The location of the lib directory will vary depending on what servlet container you're using. DWR is designed to work with any standard servlet container so feel free to use the one you're most comfortable with.

Once the DWR jar file is in the lib directory, you'll need to configure the Web application to use it. Add the following lines to the Web.xml file, located in the WEB-INF directory:

    <servlet>
      <servlet-name>dwr-invoker</servlet-name>
      <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
      <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>dwr-invoker</servlet-name>
      <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>

The <param-name> and <parm-value> tags between the <init-param> tag is optional but I've found the debug page to be extremely useful, however, you'll want to make sure it's turned off when you deploy the application. The debug page will be discussed in greater detail later in this article.

Now you'll need to create a dwr.xml file in the WEB-INF directory. This is the DWR configuration file and for the "Hello World" application you'll only need to put the following lines in it.

<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd">

<dwr>
   <allow>
     <create creator="new" javascript="ajaxFunctions">
       <param name="class" value="ajaxDemoHello.model.ajaxFunctions"/>
     </create>
   </allow>
</dwr>

The DWR configuration file defines what classes DWR can create for remote use by JavaScript. In the example above, I defined "ajaxFunctions" to be used by JavaScript to call a Java class named ajaxFunctions in the ajaxDemoHello.model package. The name of the class doesn't have to be the same name that you defined for JavaScript's use; I just find it convenient to keep the names the same.

There are a couple of restrictions to the names that can be used for classes and methods. You can't use any JavaScript reserve words. Most of the words that are reserved in JavaScript are also reserve words in Java so this is normally not an issue but something to keep in mind.

You'll also want to avoid overloaded methods because it's hit or miss on which method gets called. This is because JavaScript doesn't typecast its variables so DWR has to guess which overloaded method to call based on what the variable contains for data.

As an example, let's say there are two methods that are overloaded, one accepting an int as the argument and the other accepting a String as the argument. You then try to call the method that accepts the String as the argument but the String contains "42." DWR may interpret the 42 as the number 42 and call the method that accepts the int.

The "Hello World" application will have two files, an index.html file that contains the static Web page of the Web application and the ajaxFunctions class that contains the methods that DWR will use to implement the AJAX functionality of the Web page shown in Listing 1.

Once the "Hello World" Web application is deployed, you can test the AJAX functionality by using the DWR's debug page shown in Listing 2. To access the debug page you'll want to point your Web browser to http://{your Web server}:{port}/{your Web app}/dwr/, this will bring up a page that will look like Figure 1.

All classes that are configured in the dwr.xml file will be listed here. To test a class, click on the class name. In this case, there's only one class so click on the ajaxFunctions link and you should see a page that looks like the page in Figure 2.

One of the things that makes DWR so easy is this debug page. Not only does it let you test the AJAX functionality of each method but it also tells you what JavaScript files to include in the Web page to access this class with DWR.

About halfway down the page, you'll see the sayHello() method listed with an Execute button next to it. If you click the button, and everything is configured correctly, you'll see the "Hello from AJAX and DWR" message appear next to the Execute button.

The top of the debug page lists three scripts; two are listed as required and one is listed as optional for the ajaxFunctions class. The examples in this article need a function from the optional utility script, so you'll have to put all three scripts in the index.html page. These scripts should go in the head of the HTML page. You can simply cut each script line from the debug page and paste them into your code.

To display the string returned from the sayHello method, we have to write a JavaScript function to act as the callback function for the sayHello method, but DWR makes this easy too. Listing 3 contains this JavaScript function.

This creates a JavaScript function called displayHello that accepts one argument (remember JavaScript doesn't typecast its variables). The only line in the displayHello function uses the setValue function of the DWR utility script. This function takes the value of the second argument (displaystring) and alters the contents of the element with the id of the first argument (message). This will work with almost all HTML elements that use an id tag.

In the index.html page, change the line that displays "Click me" to the following line:

<a onClick='ajaxFunctions.sayHello(displayHello)'>Click Me:</a> <div id="messages">

Clicking on the "Click Me:" will trigger the sayHello method of the ajaxFunctions class. You may remember that the sayHello method doesn't accept an argument, but the line above passes one. The first argument in a method that's called with DWR is the JavaScript callback function that the output of the method is passed to. In this case the output of the sayHello method is passed to the displayHello javaScript function that we created above. The sayHello method doesn't accept any arguments but if it did the arguments would be added after the callback function.

The <div id="messages"> at the end of the line is where the DWRUtil.setValue will put the hello message. The new index.html file is in Listing 4. If the JavaScript files to include (those listed on the debug page) are different than the ones in Listing 4, change them to match the ones on the debug page.

With this new index.html deployed you'll be able to click on the "Click Me:" and the hello message will appear.

Congratulations, you've created your first AJAX-enabled Web application.

Here's a checklist of what's needed to integrate DWR with a Web application:
I.   Copy the dwr.jar file to the lib directory of the Web application.
II.   Edit the web.xml file so the Web application will recognize DWR.
III.   Create the dwr.xml file to configure DWR.
IV.   Write the Java class that DWR will use for the AJAX functionality.
V.   Add the AJAX functionality to your Web application.

That's really all that's needed to develop an AJAX-enabled Web application with DWR.



Page 1 of 2   next page »

About Jon Hoffman
Jon Hoffman is a systems operation manager. His primary responsibility is developing Web-based applications in Java. DWR has allowed Jon to turn Web sites and Web pages into Web applications.

Don wrote: I have a couple of comments/criticisms on this article. The first is that the ajaxFunctions Java class doesn't follow the standard Java naming conventions for a class. I believe this was done to make it look more natural in the html pages, but I think when deviating from a well known standard it's good to briefly state why. The second is that the ajaxFunctions class is essentially a Facade over other functionality, but the author never really states that or recommends using a Facade pattern instead of directly accessing beans or a DAO layer. The third comment I have is that DWR seems to require putting HTML back into our java code. One of the nice things aboutJSP rendering is that you don't have a bunch of println or string concatenations to build the HTML code directly in your servlet class. It's seems ...
read & respond »
AJAXWorld News Desk wrote: Putting AJAX functionality into your Web application can be a daunting task when you're first learning AJAX. After all you're a Java programmer not a JavaScript programmer. It can also be very frustrating having to learn how the different browsers handle XMLHttpRequests. It's been reported, however, that Internet Explorer 7 will support native XMLHttpRequests rather than requiring the developer to make ActiveX requests. This will make a Web developer's life a lot easier.
read & respond »
LATEST JAVA STORIES & POSTS
JavaOne 2008: A Developer's Perspective
This is my third JavaOne. Many topics were discussed, friendships were made, new partnerships were started. I must say things have changed a lot and stayed the same yet again, here are my thoughts in no particular order, bear in mind that they do not represent the opinion of my c
3rd International Virtualization Conference & Expo: Themes & Topics
From Application Virtualization to Xen, a round-up of the virtualization themes & topics being discussed in NYC June 23-24, 2008 by the world-class speaker faculty at the 3rd International Virtualization Conference & Expo being held by SYS-CON Events in The Roosevelt Hotel, in mi
A Lightweight Approach to SOA and BPM in Java Using jBPM
SOA is mostly associated with technologies such as BPEL, SCA and Web Services. But does SOA really imply these technologies? In this session we will show how you can use the service oriented approach while staying inside the Java world. jBPM is a powerful lightweight framework th
Case Study: Java and the Mac
This is the story of a Mac application developer (okay - it's about two of them) who set out on a quest to find an application development tool based on Java so his boss would let him develop on the Mac platform, which he loved. There was only one catch - he had to find a tool th
eApps Hosting Now Offers the GlassFish Java Application Server in VPS Hosting Plans
eApps Hosting announced that the GlassFish Open Source Application Server for Java EE 5, from the GlassFish community project, is now available as a click installable application service in low cost Virtual Private Server (VPS) hosting plans. The eApps Hosting service has support
The 4 Core Principles of Agile Programming
One of the things I really enjoy at the moment is the recognition and adoption of agile programming as a fully fledged powerful way to deliver quality software projects. As its figurehead is a group of very talented individuals who have created the agile manifesto (http://agilema
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE
BREAKING JAVA NEWS
Five Sun Microsystems Women Honored with Prestigious Awards
Sun Microsystems, Inc. (NASDAQ:JAVA) today announced that five Sun women have been awar