DWR Java API

DWR has a deliberately small Java API. Usually, as a web application developer you will only need to depend on WebContext / WebContextFactory if you are using reverse ajax, you may in addition need ServerContext / ServerContextFactory. These classes are located in the org.directwebremoting package.

WebContext and ServerContext are your connection to other parts of DWR and the general servlet API. WebContext is used when you are in a DWR thread. It uses a ThreadLocal variable to connect you to the running container. ServerContext can be used outside of a DWR thread, but as a result you will need to pass it a ServletContext so it knows where DWR is running.

These classes give you to access to the standard HTTP servlet objects:

You use WebContext like this:

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
///
WebContext ctx = WebContextFactory.get();
req = ctx.getHttpServletRequest();

It is important that you treat the HTTP request and response as read-only. While HTTP headers might get through OK, there is a good chance that some browsers will ignore them. Any attempt to change the HTTP body WILL cause DWR errors.

See also the JavaDoc for DWR in general, or the specific page for WebContext.

Alternative Method

It is possible to get access to the HTTP servlet objects without writing code that depends on DWR - just have the needed parameter (i.e. HttpServletRequest, HttpServletResponse, HttpSession, ServletContext or ServletConfig) declared on your method. DWR will not include it on the generated stub and upon a call of the method it will fill it in automagically.

For example if you have remoted a class like this:

public class Remote {
  public void method(int param, ServletContext cx, String s) { ... }
}

Then you will be able to access it from Javascript just as though the ServletContext parameter was not there:

Remote.method(42, "test", callback);

DWR will do the work of filling in the parameter for you.

There is one slight caveat with this method. You should ensure you are not using the 'callback function as first parameter' idiom, instead use the 'callback as last parameter' or 'callback in meta-data object' idioms. See the scripting introduction.