Welcome!

AJAX & REA Authors: John Funnell, Bob Little, Kevin Hoffman, Maureen O'Gara, Onkar Singh

Related Topics: Java, AJAX & REA

Java: Article

AJAX: The Easy Way

With Java and DWR

Now that you've seen how easy it is to add AJAX functionality to your Web application with DWR, let's create the baseball statistics Web application.

When the application is first started, a list of available positions appears to the left of the screen that can be clicked on. The page should look like Figure 3.

After you click on a position, a list of players that are available for that position will appear in a dropdown selector. Figure 4 shows what it looks like if you selected center fielder.

Once a player is selected, his statistics will appear. Figure 5 shows what this looks like.

Now that we have a basic idea of how the Web application is supposed to function, it's time to start the development. Steps one and two will be the same for almost all applications. Before you go live with the Web application, just remember to disable the debug page.

For the baseball statistics Web application, step three will also be the same as the "Hello World" application. I usually name the Java class that handles the AJAX functionality ajaxFunctions.java just to keep it consistent between applications. Below is the dwr.xml file for the baseball statistics Web application:

<!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="com.thelinuxdog.model.ajaxFunctions"/>
     </create>
   </allow>
</dwr>

Step four is to develop the Java class that DWR will use for the AJAX functionality. Before this class can be developed, the class that will handle all the data access functions needs to be written. Normally this class would use a database to store the data, but for simplicity's sake this class will store the data in an array of Strings. Listing 5 contains the dataFunctions class.

The dataFunctions class contains two methods. The first method, returnNames, returns a list of names and the number of the players for a given position. The position is passed to the method through its only argument.

The second method, returnStats, returns an array of Strings that contains the statistics for the player with a given number. The player's number is passed to the method through its only argument.

Listing 6 contains the ajaxFunctions class.

The ajaxFunctions class also contains two methods. The first method, displayNames, displays the dropdown box that contains the players for a given position. The method accepts a String that contains the position that you want to obtain the list of players as its only argument.

The displayNames method begins by getting a list of players who can play the given position from the returnNames method of the dataFunctions. It then begins to build the HTML code for the dropdown box by defining a form with a name of playerform.

The next line defines the select box. The onChange function of the select box calls the displayStats method of the ajaxFunctions class with DWR. This is very similar to the onClick method in the "Hello World" Web application except we're passing two arguments this time because the displayStats method will accept one argument. Keep in mind the first argument passed to a method with DWR is the JavaScript callback function that will accept the output of the Java method. The second argument of the function uses this.options[this.selectedIndex].value to get the number of the selected player and that number is what's passed to the displayStats method.

The options for the select box are then added using the list of names and numbers of the players that were returned from the returnNames method. The value of the option is the player's number and the element is the player's name. The String that represents the HTML code for the select box is then returned, which DWR will then pass to the JavaScript callback function to display on the Web page.

The second method in the ajaxFunctions class is called displayStats. This method returns the HTML code to display the statistics for the player with the number that's passed to the displayStats method in its only argument. This function is similar to the returnNames method. It begins by getting the data needed from the returnsStats method of the dataFunctions class and then builds the HTML code to display the statistics. The method then returns the String that contains the HTML code to display the statistics.

The Web application can be deployed at this point to test the ajaxFunctions class with the DWR debug page. After the application is deployed, point the Web browser to http://{your Web server}:{port}/{your Web app}/dwr/ and you should see the debug page if everything is configured correctly. If you click on the ajaxFunctions link, you'll be taken to the ajaxFunctions debug page, which will also list the JavaScript files needed by the Web application to use the ajaxFunctions class with DWR. Listing 7 contains the index.jsp file for the baseball statistics Web application. Remember to substitute the links to the JavaScript files with the ones from your ajaxFunctions debug page.

You may have noticed that in the ajaxFunctions class the displayStats method was called by the displayNames method. Calling an AJAX method from another AJAX method is perfectly fine under one condition, the JavaScript functions needed by the AJAX method has to be on the static HTML page and not created by the AJAX method. For example, when the displayStats method is called it sends the output to the JavaScript callback function called displayStatsJS. Therefore, the displayStatsJS function needs to be in the static HTML page, or in this case the static jsp page called index.jsp.

That is all there is to developing an AJAX-enabled Web application with DWR. The next question is "what do you do if the AJAX functionality doesn't function properly?" The debug page created by DWR is the first tool that I use for debugging my AJAX-enabled applications. It's good for testing if DWR is configured properly and if the functions called through DWR are working properly.

If everything appears to work properly through the debug page but the AJAX part of your Web application still isn't working, you'll need to know a little bit of JavaScript to debug your application. The most useful JavaScript command for debugging is the alert command that pops up an alert window. For example, the command alert("Hello"); pops up an alert box with the word "Hello" in it. This can be useful to see if you're getting to your callback functions and to test what's in the variables.

If I were to change the displayNameJS javaScript function to:

function displayNamesJS(data)
      {
    alert(data);
        DWRUtil.setValue("names",data);
      }

everytime the displayNamesJS function is called, an alert pop-up box that contains the HTML code that's going to be displayed on the page would appear

As you can see it's pretty easy to develop AJAX-enabled Web applications with DWR. DWR handles all of the compatibility issues with the different browsers and the asynchronous calls to the server so all you have to do is write the Java classes that DWR will use.

I've been using DWR version 1.x for a while now in my development environment and found it to be very stable. They are in the process of developing a version 2 that will introduce "Reverse Ajax," which will allow Java on the server to send JavaScript to the client.

In this article I showed how to develop AJAX-enabled Web applications by having DWR pass HTML code back to the browser. To me this is the easiest and most flexible way of using DWR, but not the only way. The DWR Web site has very good documentation and examples (http://getahead.itd.uk/dwr/). I'd really recommend that if you plan on using DWR in your production environment that you spend a little time reading the full documentation to find the best way of using DWR for your project.

More Stories By 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.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Don 11/13/06 01:03:06 PM EST

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 would have been nice to touch upon this. It's an obvious drawback or at least something that will make many people pause before try DWR. Other AJAX libraries allow you to make use of Java's JSP rendering to format and return HTML content.

AJAXWorld News Desk 10/19/06 12:09:29 PM EDT

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.