Adventures in DWR

I was adding a bit of UI zing to a web application yesterday, and decided that a particular requirement would benefit from some AJAX capabilities.

I’ve used a bit of AJAX in the past, and was pleasantly surprised at how relatively easy it was. At that time, I cut and pasted some JavaScript from the web. This time I decided to try my hand at a pre-canned AJAX framework.

So I downloaded DWR, and dropped it into my application. I wanted to dynamically fill a selection list with some values from the server; this is a pretty common requirement, and there’s even an example in the DWR documentation.

Here’s all it took:

First, I created a Java class that could provide my selection values. The initial dumb implementation looked like this:

public class UserAjaxService {
  public String[] getSelections() {
    return new String[] { "Fred", "Barney", "Wilma" };
  }
}

There were no special interfaces or coding conventions that needed to be worried about.

Next, I created a DWR configuration file:

<!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="UserAjaxService">
      <param name="class"
          value="ca.intelliware.example.ajax.UserAjaxService"/>
    </create>
  </allow>
</dwr>

I put this file (called “dwr.xml”) in my web application’s WEB-INF. I also dropped the dwr.jar file in my WEB-INF/lib and added a small number of additions to my web.xml file.

Then I started up my app. By going to:

http://localhost:8080/myApp/dwr/

I could see my UserAjaxService listed on a page generated by DWR. A link took me directly to a page describing the methods available in my service, and allowed me to invoke those methods via automatically-generated JavaScript.

That same page instructed me on how to get the same functionality on my application page. Just copy a few <script> references onto my page:

<script type='text/javascript' src='/dwr/interface/UserService.js' />
<script type='text/javascript' src='/dwr/engine.js' />
<script type='text/javascript' src='/dwr/util.js' />

I didn’t create any of these scripts; they’re auto-generated by the DWR engine.

Lastly, I added a bit script on a particular button:

<input name="searchCriteria"
       id="searchCriteria" type="text" value="">
<input type="button" value="Look Up&gt;&gt;"
     onclick="UserService.getUserNames(getInputValue('searchCriteria'), fillList);" />
<script>
var fillList = function(data) {
  DWRUtil.removeAllOptions("myList");
  DWRUtil.addOptions("myList", data);
}
</script>
<select size="4" id="myList" name="user"></select>

And that was it. In minutes, I had the AJAX functionality up and running.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply