First DWR program

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 HelloWorld.java) 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 download the commons-logging-1.2-bin.zip.


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


<servlet>
  <display-name>DWR Servlet</display-name>
  <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>


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

<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
    "http://getahead.org/dwr/dwr30.dtd">
<dwr>
  <allow>
    <create creator="new" javascript="Demo">
      <param name="class" value="com.javaxp.dwr.HelloWorld"/>
    </create>
  </allow>
</dwr>

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

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

package com.javaxp.dwr;

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





write in url ---> http://localhost:8080/DWRExample/dwr


then after this u will be redirected to a page and there will be a hyper link availabe  name demo click on that
And futher u will see ur java class method with a box and a execute button
now finally enter your name in the box like his --> "yourname"
and hit the execute button and u will see the the output like this --> hello yourname !!!

Comments

Popular Posts

Image