The custom converter is done independently of the action, form or DTO.

First step is to implement the interface org.apache.commons.beanutils.Converter.

Keep in mind that the converter you are writing uses the appropriate converter for the original class. So, if you were converting from a String to a Date, you would create a String converter. And vice versa, if you were converting from a Date to a String you would create a Date converter. Example below

Then, to override the standard converters, you call:
ConvertUtils.register(<Your converter class>, <class to use converter on>.class);


First parameter is your new converter, and the second is the class its used for. I call this in a static initializer of a utility class, you just need to make sure its called before any validations occur, and it only needs to be done once.

Since we are interested in customizing conversions from String to Date, I override the String converter:

public class StringConverter implements Converter{
public Object convert(Class type, Object value) {
Object returnObj = null;
if (value != null) {
if (value instanceof Date){
returnObj = dateFormatter.format((Date)value);
} else if (value instanceof BigDecimal){
returnObj = decimalFormatter.format((BigDecimal)value);
} else {
returnObj = value.toString();
}
}
return returnObj;
}
}


I've left out some properties, their getters and setters, but I think you get the gist of what I'm doing. Now, I register this converter as such:

ConvertUtils.register(new StringConverter(), String.class);

I actually have a utility class, where the register is done in the static initializer. I suppose another way would be to use a servlet that loads prior to Struts.. Or if your Actions have a base class, etc...

Maybe there's a more elegant way of doing that. This is what I've come up with. If someone has a better way, post please, I'm always looking for more elegant ways of accomplishing stuff like this.

Jason King wrote:

Could you point us at some code that does this? Do you customize in the action, the form or the DTO?


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to