Friday, April 22, 2011

How to create a custom TypeConverter in Stripes

Stripes uses TypeConverters to take convert JSP responses (typically a serialized form), and convert it back into Java types. Most conversions that you will need are already provided by default (see like below), but I found with Enums sometimes special cases are needed. There are ways to register customer converts globally, but in this case I just needed it for a specific case.

Example Custom TypeConverter
public class MyEnumeratedTypeConverter extends EnumeratedTypeConverter{

@Override
public MyEnum convert(String input, Class targetType, Collection errors) {
  MyEnum type = //Your conversion logic here.
  if(type == null){
    errors.add(new ScopedLocalizableError("converter.enum", "notAnEnumeratedValue"));
  }
  return type;
  }
}

Once the class is defined, it needs to be wired up in the ActionBean. In the below snipped, note the converter param in the @Validate annotation.

Example Wire-Up
@Validate(required = false, on={"fetch"}, converter=MyEnumeratedTypeConverter.class)
public void setMyEnums(Collection myenums){
  this.myenums = myenums;
}

See Also:

No comments:

Post a Comment