Monday, June 18, 2012

DWR Hello World example

DWR - Direct Web Remoting

DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible. In simple words DWR is Easy Ajax for Java. Unlike AJAX you don't have to write codes to get XHTML object or check for state change etc. To know more about DWR, click here.

DWR is supported by almost all browsers like Firefox,Internet Explorer,Opera and Safari. To know more, click here.

About the example

We will create a simple java class (i.e with a method sayHello() which will accept a name and print Hello name. We can call this java fuction with JavaScript in a browser. Same as Ajax call without refreshing the whole page.

Below are the steps to run the example.

1. For running the below example you need to add below mentioned JAR file in lib folder of your web project.

  • dwr.jar
  • commons-logging-1.1.1.jar 

For downloading dwr.jar, click here
commons-logging-1.1.1.jar, click here.

2. Add the DWR servlet definition and mapping to your application's web.xml. This is just like defining a normal servlet.

  <display-name>DWR Servlet</display-name>

3. Create the DWR configuration file (dwr.xml). Create this file in WEB-INF folder alongside web.xml.

    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
    <create creator="new" javascript="Demo">
      <param name="class" value="com.javaxp.dwr.HelloWorld"/>

Note : we will create a class HelloWorld in next step.

4. Now we will create our Java Class (i.e.

package com.javaxp.dwr;
public class HelloWorld {
                public String sayHello(String name) {
                                System.out.println("sayHello called : "+name);
                                return "Hello "+name+"!!";

To test the setups done so far go to the below link. (Assuming our webproject is DWRExample ) http://localhost:8080/DWRExample/dwr

Clicking Demo you should see below screen.

5. Now lets create our custom JSP (lets say index.jsp) to test DWR.

<title>DWR Hello World Example</title>
<script type='text/javascript' src='/DWRExample/dwr/engine.js'></script>
<script type='text/javascript' src='/DWRExample/dwr/interface/Demo.js'></script>
<script type='text/javascript' src='/DWRExample/dwr/util.js'></script>
<script language="javascript">
function callDWR() {
Demo.sayHello($("name").value, callBack);
return false;
function callBack(data) {
if (data != null && typeof data == 'object')
alert(dwr.util.toDescriptiveString(data, 2));
dwr.util.setValue('greet', dwr.util.toDescriptiveString(data, 1));
DWR Hello World Example
<form onsubmit="return callDWR();">
<input id="name" type="text"/><span id="greet"></span>
<input type="submit" value="submit"/>