YOUR FEEDBACK
Immo Huneke wrote: A well written article, an ingenious solution to a real problem often encountere...


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
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
MXDJ TOP LINKS YOU MUST CLICK ON !


AJAX: The Easy Way
With Java and DWR

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.


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.

YOUR FEEDBACK
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 a step backwards to start putting HTML rendering in our Java code. It wo...
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.
LATEST FLEX STORIES & POSTS
Curl announced the release of Curl Data Kit Data Services (CDK-DS) for enterprise developers building new applications using Adobe Flex or Flash, as well as developers upgrading existing Curl applications. This addition to the Curl Rich Internet Application (RIA) Platform is an impleme...
Adobe and Intel plan to collaborate on porting Adobe’s Flash widgetry to Intel’s Media Processor CE 3100, a way to put Flash-enhanced web content and rich Flash applications on television. The chip is bound for cable set-top boxes, Blu-ray Disc players, digital TVs and retail-conne...
Across Systems, the provider of the Across Language Server, and IAI (Institute for Applied Information Science at Saarland University) have expanded their relationship and broadened the integration of their two technologies. The direct connection of the Controlled Language Authoring To...
Cocomo adds to the existing technology in the Flash Platform and provides further choice in terms of how you build and deploy collaborative applications - it does not replace the approach provided by BlazeDS/LCDS. Whilst the Cocomo service removes the complexity associated with deploym...
Until recently Flex developers had the option of using the free, open source SDK (together with a text editor of choice) or purchasing Flex Builder, Adobe’s Eclipse-based IDE for building, debugging, profiling and deploying Flex applications. Whilst Silverlight will remain an obvious...
Adobe’s AIR for Linux, the runtime engine that supports rich Internet apps (RIAs), has caught up with its Windows and Mac siblings. The company has released AIR 1.5 for Linux, the first time the Linux desktop variant has made it as a production-grade, Adobe-supported release. And now...
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

Click Here

SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE