DWR Annotations

DWR annotations can be used as a replacement as well as in conjunction with dwr.xml.

Annotation support was written by Maik Schreiber.

Setup

To use DWR with annotations you need to specify a different DWR controller servlet in your web.xml:

<servlet>
  <description>DWR controller servlet</description>
  <servlet-name>DWR controller servlet</servlet-name>
  <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
  <init-param>
    <param-name>classes</param-name>
    <param-value>
      com.example.RemoteFunctions,
      com.example.RemoteBean
    </param-value>
  </init-param>
</servlet>

The classes servlet parameter must provide a comma-separated list of the fully-qualified class names of all annotated classes to be used with DWR.

The syntax for inner classes is to use '$' notation (as used by Class.forName()) rather than '.' notation (as used by import statements). For example, use java.util.Map$Entry and not java.util.Map.Entry.

Remote Class Access

To make a simple class available for remote access, use the @RemoteProxy and @RemoteMethod annotations:

@RemoteProxy
public class RemoteFunctions {
    @RemoteMethod
    public int calculateFoo() {
       return 42;
    }
}

Any method not annotated with @RemoteMethod will not be available for remote access.

To use a scripting name different from the class name, use the name attribute of @RemoteProxy:

@RemoteProxy(name="Functions")
    public class RemoteFunctions {
}

The @RemoteProxy has options available please see the Java docs for more details.

Object Conversion

To make simple bean classes available for remote access, use the @DataTransferObject and @RemoteProperty annotations:

@DataTransferObject
public class Foo {
    @RemoteProperty
    private int foo;

    public int getFoo() {
        return foo;
    }

    @RemoteProperty
    public int getBar() {
        return foo * 42;
    }
}

To use more sophisticated converters see the converter attribute of the @DataTransferObject annotation. Here is an example that configures the Hibernate converter and tells DWR to exclude propertyToExclude from serialization.

// Standard Annotation Configuration
@DataTransferObject(converter=H3BeanConverter.class,
params = @Param(name = "exclude", value = "propertyToExclude"))  

Note: If you are using Spring you will need to use the type attribute:

// Spring Annotation Configuration
@DataTransferObject(type="hibernate3",
params = @Param(name = "exclude", value = "propertyToExclude"))