Field-based conversions:
1, write a class, inherit Defaulttypeconverter, overwrite Convertvalue (Object value, class ToType)
1 PublicObject Convertvalue (object value, Class totype) {2 if(value==NULL|| totype==NULL|| Totype!=java.util.date.class )3 {4 return false;5 }6 if(Valueinstanceofjava.lang.string[])7 {8String[] Strs=(string[]) value;9 if(strs[0]!=NULL&& strs[0].length () >0)Ten { One Try { ASimpleDateFormat sdf=NewSimpleDateFormat ("yyyy-dd-mm"); - returnSdf.parse (strs[0]); -}Catch(ParseException e) { the /* - * In the STRUTS2 framework, the custom type converter, - * If we do not throw exceptions manually, the STRUTS2 framework catches only exceptions, but does not throw them. - * So the framework will assume that the conversion of the type converter succeeds to the successful page. + */ - Throw NewRuntimeException (e); + } A } at } - return NewDate (); -}
2. Under the folder that invokes the conversion transformation class, create a new: Class name _conversion.properties, which configures the full name of the class value= key= to be converted (cn/.../. Conver. )
1 birthday=cn.test.type.dataconver
3, we know that there is a possibility of conversion failure, so we need to display the conversion failure information
<%@ taglib uri= "/struts-tags" prefix= "s"%>
<s:fielderror fieldname= "User.birthday"/>
* But such a failure message is in English, so we need to display the information in Chinese under the class folder, create a new XML file, inside the set
xwork.default.invalid.fieldvalue= hint message ' {0} '. ({0} represents a field)
If you want to personalize the field, you can add the following:
invalid.fieldvalue. Field name = prompt information
* Registering XML in Struts.xml
1 <!-- 2 Configure all resource files, omit the suffix name, and if multiple resource files are configured, separate with ",". Not just an internationalized resource file3 * Type converter Error prompt resource file (omit suffix name)4 -5 <constantname= "Struts.custom.i18n.resources" 6 value= "Cn.test.type.converter,cn.itcast.i18n.resources">7 </constant>
Can also be based on the transformation of the class: Transform the file unchanged, in the class folder under the new Xwork-conversion.propertices file, the inside configuration
Type to convert (java.utiils.xxx) = Full path of the transformation Class (CN.X.XXX)
STRUTS2 Type Conversions