Direct Web Remoting – A Tutorial


The DWR / Direct Web Remoting is an open source solution under the Apache license for the developer who wants to use AJAX and XMLHttpRequest in an easy way.

A Step by Step example:

1) Create the java service class :

package com.example.dwr;

public class DWRPersonService {

public Person[] getAllPersons() {

Person[] list = new Person[3];

/* ………………………..
Call your Ejb / DAO here
and populate values in the array
………………………..
*/

Person info = null;
info = new Person();
info.setId(1L);
info.setName(“sam”);
info.setCity(“bangalore”);
info.setCountry(“india”);
list[0] = info;

return list;
}//end of getAllPersons

}//end of Class

2) Create the java bean class. (can be your Info or Transfer Object)

package com.example.dwr;

public class Person {

private Long id;
private String name;
private String city;
private String country;

/*
* Getters and Setters are defined here
*/

/**
* @return the id
*/
public Long getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

// ……………

}//end of Class

3) Configure DWR in WebXml

Start by specifying DWR’s existence in the web.xml

<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.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>
</servlet>

Include dwr.jar in the WEB-INF/lib folder.

Place the scripts and css files in the respective folders.

You can download the latest jar from DWR Site

For support of autocomplete feature download the script.aculo.us-js-1.x.zip

4) Configure the dwr.xml

<!DOCTYPE dwr PUBLIC
“-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN”
http://www.getahead.ltd.uk/dwr/dwr10.dtd”&gt;
<dwr>
<allow>
<create creator=”new” javascript=”JDate”>
<param name=”class” value=”java.util.Date”/>
</create>

<create creator=”new” javascript=”DWRPersonService”>
<param name=”class” value=”com.example.dwr.DWRPersonService”/>
<include method=”getAllPersons” />
</create>

<convert converter=”bean” match=”com.example.dwr.Person”></convert>
</allow>
</dwr>

We specify here to create a new js file for DWRPersonService.
The DWR engine will generate a file DWRPersonService.js at runtime
with the function getAllPersons.

The DWRPersonService.js created at run time by DWR Engine, looks as follows:

// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};

if (dwr.engine == null) dwr.engine = {};

if (DWREngine == null) var DWREngine = dwr.engine;

if (DWRPersonService == null) var DWRPersonService = {};

DWRPersonService._path = ‘/dwr-sample/dwr’;

DWRPersonService.getAllPersons = function(callback) {
dwr.engine._execute(DWRPersonService._path, ‘DWRPersonService’, ‘getAllPersons’, callback);
}

5) Create your Jsp.

Include the following js files from DWR.

<script type=’text/javascript’
src=’/dwr/engine.js’ />
<script type=’text/javascript’
src=’/dwr/util.js’ />

Also include the js file created for you, as defined in dwr.xml

<script type=’text/javascript’
src=’/dwr/interface/DWRPersonService.js’ />

Include the following js and css files for AutoComplete feature.

<link rel=”stylesheet” type=”text/css”
href=”/styles/autocomplete.css”/>
<script type=”text/javascript” src=”/scripts/prototype/prototype.js”/>
<script type=”text/javascript” src=”/scripts/script.aculo.us/effects.js”/>
<script type=”text/javascript” src=”/scripts/script.aculo.us/controls.js”/>
<script type=”text/javascript” src=”/scripts/autocomplete.js”/>

Create a text field with id personName. Create a div with the class auto_complete.
Instantiate the function AutoCompleter which takes the following arguments.
i)Id of the textField
ii)Id of the autocomplete Div for this textField
iii)function to populate the list – uses DWR
iv)Optional arguments like valueSelector – property to be listed from the Bean object, chioces – maximum number of choices to be displayed etc.
Finally, call the method DWRUtil.useLoadingMessage on body onLoad.

<script language=”javascript”>
function updatePersonList(autocompleter, token) {
DWRPersonService.getAllPersons(function(data) { autocompleter.setChoices (data); });
}
</script>

<body onload=”DWRUtil.useLoadingMessage();”>

Search Person: <input id=”personName” type=”text” style=”width:250px;” / >

< div id=”personListDiv” class=”auto_complete” > </div>

<script type=”text/javascript”>
new Autocompleter.DWR(‘personName’, ‘personListDiv’, updatePersonList,
{ valueSelector: function(obj){ return obj.name; }, partialChars: 1, choices: 10 });
</script>
</body>

In the above method the arguments are as follows :

new AutoCompleter.DWR(textFieldName, associatedDivName, methodForPopulatingList, optionalParams)

OptionalParams:
ValueSelector : the property of the bean that has to be shown in the autocomplete list. For example, ‘name’ property from ‘Employee’ bean.

PartialChars : Minimum number of characters to be entered in order to begin matching. Default value is 2.

Choices : Maximum number of items to be shown in the drop down.

Run your application and see DWR in action !!!






Update: 21/10/2009   (Since I am getting a lot of requests, I am attaching the zip here. Take a look!)

Sample with Source Code  ZIP: http://dl.getdropbox.com/u/2000367/Dwr_Ajax.zip

Comments are Welcome!


Advertisements

17 thoughts on “Direct Web Remoting – A Tutorial

  1. Pingback: 2010 in review « :. Samjosh | Random Thoughts .:

  2. hi..
    how to call autocomplete on dynamically created textbox..
    plz give the code for dynamically creating textbox and how to call autocomplete on that..
    plz rply

  3. hi i succeeded in calling autocomplete on dynamically created textbox..
    but know my problem is that …i want to retrieve names from database..
    and than give it to autocomplete…
    how to do that…I have created connection with database retrieved all the names in ArrayList .can u plz tell how to achieve it…

  4. @sup, thats great..
    retrieving names from database is simple really..
    In the service class similar to DWRPersonService in this example, write JDBC / SQL statements to fetch whatever data u want from database ..
    eg) SELECT name FROM PERSON
    and then set the values in your java bean and add it to the list. hope it helps.

    Or u can share a link to ur code which i can maybe have a look at and help if i can.

  5. thankyou..i will share my code with u.i dont have it today..
    I have created database connection.also set java bean.
    what should be the return type of the method i am calling??can it be list.
    in ur example u have returned the person class array.
    In my bean I have name variable,getter setter method for that.
    so plz can u tell wht should i do..

  6. yea.. add your bean object to an array [ like adding Person bean to array in eg. above] . Return type should be array of bean objects.

  7. wht should be size of person array
    as i dont know how no. of names are there in the database

  8. but i dont know names can be more than 100..
    as i told i have to retrieve name from database..in my bean there are getter setter for name…so can you plz give the code as example…

  9. hi..
    i have done it..thanks a lot…
    but know my problem is i want to display address and city immediately after I select name from autocomplete list..
    I dont want on click event of button…

  10. I am getting the following javascript error.i get this error when i enter first character of name in textbox :—
    ‘elem.toLowerCase.indexOf’ is not a function

    I get this error for few characters like when i press d i get all the names starting with d.
    but when i press r i get the above error..plz give me solution

  11. hi..
    my problem is solve…thanks
    now i want to call different function after selecting name from autocomplete…this callback function should be called automatically after selecting name and not on button click..
    rply..

  12. can u post populating dropdown list using dwr technology as above….as a downloadable file
    Thanks in advance

  13. Hey! Quick question that’s totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone. I’m trying to find a theme or plugin
    that might be able to correct this problem. If you have any recommendations,
    please share. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s