Wednesday 20 June 2012

Type Conversion in struts 2.0

Struts knows how to display and convert the string "Windows XP SP3" and other built-in data types, but it does not know what to do with the the property of Environment type. So, it simply called the toString() method on the class. To resolve this problem, let us now create and register a simple TypeConverter for the Environment class. Create a class called EnvironmentConverter.java with the following.
package com.tutorialspoint.struts2;

import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;

   public class EnvironmentConverter extends StrutsTypeConverter {
      @Override
      public Object convertFromString(Map context, String[] values, 
                                      Class clazz) {
      Environment env = new Environment(values[0]);
      return env;
   }

   @Override
   public String convertToString(Map context, Object value) {
      Environment env  = (Environment) value;
      return env == null ? null : env.getName();
   } 
}
The EnvironmentConverter extends the StrutsTypeConverter class and tells Struts how to convert Environment to a String and vice versa by overriding two methods convertFromString() and convertToString(). Let us now register this converter before we us it in our application. There are two ways to register a converter. If the converter will be used only in a particular action, then you would have to create a property file needs to be named as '[action-class]'-converstion.properties, So, in our case we create a file called SystemDetails-converstion.properties with the following registration entery:
environment=com.tutorialspoint.struts2.EnvironmentConverter
In the above example, "environment" is the name of the property in the SystemDetails.java class and we are telling Struts to use the EnvironmentConverter for converting to and from this property. However, we are not going to do this, Instead we are going to register this converter globally so that it can be used throughout the application. To do this, create a property file called xwork-conversion.properties in the WEB-INF/classes folder with the following line:
com.tutorialspoint.struts2.Environment = \
            com.tutorialspoint.struts2.EnvironmentConverter
This simply registers the converter globally, so that Struts can automatically do the conversion every time it encounters an object of type Environment. Now, if you re-compile and re-run the program, you will get a better output as follows:

System Info
Obviously, now result is better which means our Struts convertor is working fine. This is how you can create multiple convertors and register them to use as per your requirements.

No comments:

Post a Comment