Home > DWR > Direct Web Remoting

Direct Web Remoting

DWR

DWR is Open Source, available under the Apache Software License v2.

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.

DWR will generate the JavaScript to allow web browsers to securely call into Java code almost as if it was running locally. It can marshal virtually any data including collections, POJOs, XML, and binary data like images and PDF files. All that is required is a security policy that defines what is allowed.

With Reverse Ajax, DWR allows Java code running on a server to use client-side APIs to publish updates to arbitrary groups of browsers. This allows interaction in 2 ways – browser calling server and server calling browser. DWR supports Comet, Polling, and Piggyback (sending data in with normal requests) as ways to publish to browsers.

DWR provides integration with Spring, Struts, and others.

Getting Started with DWR

1. Install the DWR JAR file

Download the dwr.jar file. Place it into the WEB-INF/lib directory of your web application.

2. Install the Commons Logging JAR file

DWR depends on Commons Logging. Download the commons-logging.jar and place it into the WEB-INF/lib directory of your web application.

3. Add the DWR servlet definition and mapping to web.xml

Add the following lines to your web application’s deployment descriptor (WEB-INF/web.xml). The section needs to go with any existing sections, and likewise with the section.

DWR Servlet
  dwr-invoker  
  org.directwebremoting.servlet.DwrServlet
     debug
     true
  dwr-invoker
  /dwr/*
4. Create the DWR configuration file (dwr.xml)

Create a new file dwr.xml in your web application’s WEB-INF directory.

The DWR config file defines what classes DWR can create and remote for use by Javascript. In the example above we are defining 2 classes that are remoted and giving the classes names in Javascript.

5. Take DWR for a test drive!

Go to the browser and click the following URL, change the context name of your web application with WEBAPP-CONTEXT

http://localhost:8080/[WEBAPP-CONTEXT]/dwr/
We should see a page showing you the classes we configured in Step 4. Having followed a link you should see an index of all the methods ready for calling - simply enter the required parameters and click the execute button.

Using DWR in our web application

  • Go to http://localhost:8080/[WEBAPP-CONTEXT]/dwr/ and click on the class
  • View the source and find the line that executes the method that you are interested in.
  • Paste the text into an HTML or JSP page in your web-app.
  • Include links to the DWR JavaScript files that make the magic happen