Struts2 supports some basic type conversions. If not, you can define some types of converters by yourself.
For example, to implement the following functions:
The input format of the birthday (Date type) is required to be the above. The format supported by Struts2 is "", so we need to write our own converter.
The implementation class can be as follows:
Import java. text. simpleDateFormat; import java. util. *; import org. apache. struts2.util. strutsTypeConverter; public class DateTypeConverter extends StrutsTypeConverter {// inherits StrutsTypeConverter @ Overridepublic Object convertFromString (Map arg0, String [] value, Class toType) {// convert to Date type SimpleDateFormat sf = new SimpleDateFormat ("yyyyMMdd"); String [] params = null; try {if (toType = Date. class) {params = (String []) value; return sf. parse (params [0]) ;}} catch (Exception e) {} return null ;}@ Overridepublic String convertToString (Map arg0, Object arg1) {// convert to String type return arg1.toString ();}}
It is defined as a local converter:
In the same-level directory of the action class, create a. properties file named "Action class name-conversion. propertites" and add a key-Value Pair named "key" and "converter class name ".
birthday=cn.ljf.DateTypeConverter
Defined as global:
Create a new. properties type file in the src directory, file name: xwork-conversion.propertites, and add a key-Value Pair named value with java. util. Date as the key
java.util.Date=cn.ljf.DateTypeConverter
Handle type conversion errors:
Is the error handling process of type conversion:
If an exception occurs during type conversion, the system's conversionError interceptor will handle the exception. After the exception is processed, the system returns the logic view named input. You can use <s: fielderror/> output error information in this view. Note that action should inherit ActionSupport.