Thursday, October 19, 2006

AJAX in Java with DWR

Direct Web Remoting (DWR) is an engine that exposes methods of server-side Java objects to JavaScript code. With DWR, your client-side code need to use the XMLHttpRequest object to make asynchronous calls. You don't even need to write servlet code to mediate Ajax requests into calls on your Java domain objects (the way you do when using prototype.js). Follow these steps to implement Ajax in your application:
  1. Implement a Java class that will act as the remote interface. It can be any Java class with any methods.
  2. Configure DWR in the WEB-INF/dwr.xml file defining the methods to be exposed as shown below.

    <dwr>
    <allow>
    <create creator="new" javascript="JavascriptName">
    <param name="class"
    value="JavaClassName"/>
    <include method="method1"/>
    <include method="method2"/>
    </create>
    <convert converter="bean"
    match="beanType">
    <param name="include"
    value="attr1,attr2,..."/>
    </convert>
    </allow>
    </dwr>
  3. Define the DWR Servlet in your web.xml file:

    <servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>uk.ltd.getahead.dwr.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>
  4. Invoke the methods from client-side Javascript using the notation:
    JavaScriptName.methodName(methodParams ..., callBack)
    Where the callBack method handles the data returned from the server. You will have to include engine.js and util.js available from the DWR site.


References:

No comments:

Post a Comment

Popular Posts