Tuesday, October 2, 2012

custom converter for BigDecimal struts2

if you are trying to map a BigDecimal field in jsp to the Action, you may get exception,
to solve this exception you need a converter to convert it.

1-you need to define file by the name Action_Name-conversion.properties


attrb1=com.a.b.BigDecimalConverter
attrb2=com.a.b.BigDecimalConverter

2-add the BigDecimalConverter in the package you want


public class BigDecimalConverter extends StrutsTypeConverter{

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if(values!=null && values.length>0){
String s=values[0];
if(s!=null && s.trim().length()>0){
BigDecimal bd = new BigDecimal(s);
return bd.setScale(2, BigDecimal.ROUND_HALF_UP);
}
}
return null;
}

@Override
public String convertToString(Map context, Object o) {
return o.toString();

}