The Filters

Filters are a way to take some action either before, or after a server call, or to prevent the call from happening at all.

Filters are defined using the filter element in a dwr.xml file, using the @Filter annotation, or using the dwr:filter element in a spring namespace configuration.

<filter class="...">
  <param name="..." value="..."/>
</filter>

It is valid to have a filter either at a global level (when a child of an allow element) or at a class level (when a child of a create element).

The class attribute is required, and should contain the fully qualified name of a class that implements the org.directwebremoting.AjaxFilter interface. This interface contains a single method: doFilter, that will be familiar to anyone that has use Servlet Filters in the past.

For those using Spring namespaces, the entry in a spring beans.xml file is as follows:

<bean id="..." class="...">
  <dwr:remote javascript="...">
    <dwr:filter class="..."/>
  </dwr:remote>
</bean>

The simplest filter is a no-op filter; one that does nothing, it would look something like this (note: you must implement AjaxFilter):

package com.example;

public class NoopFilter implements org.directwebremoting.AjaxFilter {
  public Object doFilter(Object obj, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
    return chain.doFilter(obj, method, params);
  }
}

In dwr.xml, you would have something like this, for a global filter:

<allow>
  <filter class="com.example.NoopFilter"/>
  ...
</allow>

Or for a filter that only filters requests to a single class:

<allow>
  <create creator="...">
    <filter class="com.example.NoopFilter"/>
  </create>
  ...
</allow>

Filters can be configured with parameters to configure how the filter acts. The optional nested param element in dwr.xml allows us to achieve this. For example, using <param name="foo" value="bar"/> will cause DWR to call filter.setFoo("bar") just after the filter has been constructed, and before it is used.

Examples of things that you might wish to do with filters include:

DWR 3.x contains one filter which is available for simulating Internet latency while developing on a local machine. It is configured like this:

<filter class="org.directwebremoting.filter.ExtraLatencyAjaxFilter">
  <param name="delay" value="200"/>
</filter>

This configures DWR to pretend that there is a 200ms time delay on round trips to DWR. That is to say it insets a 100ms pause before and after each call. The default delay time is 100ms (50ms before and 50ms after).