Comments
jcl wrote: Hi,thank you for this tutorial I'm interested on the first way to intregate Spring and EJB3. I have tried it in a example project buy it doesn't run. I'm searching since many time a solution,but nothing. I have posted on Spring forum,but no one seems can help me. I appreciate if you can help me.Thank you Antonio
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

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.

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.


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.
Enterprise Open Source Magazine Latest Stories . . .
About 10 years ago, a quiet bunch of IT revolutionaries, tired of expensive, complicated operating systems and the resources needed to support them, created a new breed of network management software and network monitoring systems. Pioneers like Solarwinds, Groundwork, Zoho (Adventnet)...
These days the popularity of Ext JS (a JavaScript library) is gaining momentum. One of the most popular widgets within Ext JS is the DataGrid. The reason – displaying data from a database is one of the most common tasks of a web application. “Out of the box” the DataGrid has functional...
PrismTech is joining forces with Nextel Engineering Systems to deliver much-needed, highly-reliable and Real-Time data management solutions. As part of its software and services offerings, Nextel Engineering will now deliver and support PrismTech’s best-in-class suite of middleware pro...
WS-BPEL 2.0 is the dominant specification to standardize orchestration logic and process automation between Web services. The BPEL model is used to assemble a set of discrete, essentially disparate, services into an end-to-end process flow to transform the existing stateless and uncorr...
Cloud computing is a game changer. The cloud is disrupting traditional software and hardware business models by disrupting how IT service gets delivered. Entrepreneurial opportunities abound as this classic disruptive technology begins to proliferate, so it is no surprise that SYS-CON'...
The newest release of Open-Xchange builds on a consistent theme as its delivers more integration with other webmail programs like Gmail, as well as the ability to incorporate contact information – the latest includes the Yahoo address book. Open-Xchange today announced enhancements tha...
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