Struts 2 TypeConversion

TypeConversion:Struts is provided with support for data conversion while mapping from front end(jsp) to action and vice versa.

It automatically handle:string,int,date,array,collection of string etc.

But if we have a customized object then we need to write a converter.

Suppose we have a Employee object(with name as instance variable with getter and setter) as a action(TestAction) property:

private Employee employee;
public Employee getEmployee() {
      return employee;
   }
   public void setEmployee(Environment employee) {
      this.employee = employee;
   }

Then to handle conversion for this property we need to write a Converter.

public class EmployeeConverter extends StrutsTypeConverter {
   public Object convertFromString(Map context, String[] 
                                 values, Class toClass) {
      Employee obj = new Employee(values[0]);
      return obj;
   }
 
   public String convertToString(Map context, Object o) {
      Employee obj  = (Employee) value;
      return obj == null ? null : obj.getName();
   }
}

For this we need to create one property file with name action-convertion.properties specific to action properties.

employee=EmployeeConverter