The Converters

Converters are an integral part of DWR and are responsible for marshaling data between the client and the server. You must specify a converter for:

  1. The Java return type of Java methods you have exposed to DWR. In order to return a JavaScript object that can be used by the browser DWR needs to know how to marshal the Java return type into a JavaScript object.
  2. The Java parameter type of all parameters of Java methods you have exposed to DWR. In order to properly call the Java method DWR needs to know how to marshal the JavaScript object being passed from the browser into the appropriate Java object.

A number of converters deserve sections of their own:

Basic Converters

The converters for primitives, strings and simple objects like BigDecimal are all there waiting for you. You don't need a <convert ...> element in the <allow> section in dwr.xml to use them - They are enabled by default.

The types enabled by default include: boolean, byte, short, int, long, float, double, char, java.lang.Boolean, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.lang.Character, java.math.BigInteger, java.math.BigDecimal and java.lang.String

Date Converter

The Date converter marshalls between a Javascript Date and a java.util.Date, java.sql.Date, java.sql.Times or java.sql.Timestamp. As with the basic converters above, the DateConverter is enabled by default.

If you have a string (e.g. "01 Jan 2010") in Javascript, that you wish to turn into a Java Date then you have 2 options: Parse it in Javascript using Date.parse() and then pass it to the server using DWR's DateConverter, or pass it as a String and then parse it in Java using a SimpleDateFormat (or something similar).

On the other hand, if you have a date in Java which you wish to display in a usable form in HTML, then you can either transfer it as a string after using a DateFormatter on it, or transfer as a Date and then use Javascript to format it. The first option is probably easier although it does mean messing around with your converted objects, and it's doing something that it strictly view logic further from the browser. The latter option is better really and there are utilities to help you. For example:

Other Objects

It is fairly simple to create your own converter. The Javadoc for the Converter interface contains instructions. It quite rare however for this to be needed. Please make sure you understand the BeanConverter before starting to write your own Converter. Having implemented a custom converter, you need to register it with DWR. If you are using dwr.xml, there is an <init> section before the <allow> that lets you register new components. See the DTD documentation for more information.