Easy Ajax call with java classes using DWR

Dwr provides easiest way to interact with Java class by ajax request.DWR will generate the JavaScript to allow web browsers to securely call into Java code.

Here I am going to explain step-by-step process to build the DWR (Direct Web Remoting).

Step 1:Add dwr.jar to WEB-INF/lib

Step 2:Add servlet entry to web.xml


Add dwr.xml to WEB-INF

In dwr.xml need to map java classes which we want to use in ajax request.

    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"

      <create creator="new" javascript="Calculate">
      <param name="class" value="com.startwithjava.Calculate"/>

Define Bean class

package com.startwithjava;
public class Calculate {
	public int add (int x,int y) {
		return x+y;
	public int subtract(int x,int y){
		return x-y;

Javascript file configuration

Auto generated Javascript file is equivalent to java class file name.In our class case Calculate class is here so the generated javascript file name will be Calculate.js which we include to our jsp pages.

Now define a jsp page and include engine.js,Calculate.js and util.js(optional) to the jsp page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DWR Ajax Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
 <script type='text/javascript' src='/DwrProject/dwr/engine.js'></script>
    <script type='text/javascript' src='/DwrProject/dwr/interface/Calculate.js'></script>
  <script type='text/javascript' src='/DwrProject/dwr/util.js'></script>

<h1>DWR Ajax Application</h1>
<td><input type="text" id="num1"></td>
<td><input type="text" id="num2"></td>
<input type="button" id="add" value="Add" onclick="add();">
<input type="button" id="sub" value="Subtract" onclick="subtract();"></td>
<div style="font-size:18px" id="div2"></div>
<script type="text/javascript">
function add()
	var num1 = jQuery("#num1").val();
	var num2 = jQuery("#num2").val();
    Calculate.add(num1,num2,function(data) {
    	dwr.util.setValue("div2", data);
function subtract()
	var num1 = jQuery("#num1").val();
	var num2 = jQuery("#num2").val();
    Calculate.subtract(num1,num2,function(data) {
    	dwr.util.setValue("div2", data);

Now run http://localhost:8080/[you_application]/dwr this url.

DWR Application
Download Code

Leave a Reply