Detailed description of Struts2 type conversion

Source: Internet
Author: User

I. Significance of type conversion

For an intelligent MVC Framework, type conversion is inevitable. because the Request Parameters of B/S (Browser/Server) structure applications are sent to the server through a browser, these parameters cannot have a wide range of data types, so data type conversion must be completed on the server side.

The MVC Framework is a presentation layer solution that should provide support for type conversion. Struts2 provides very powerful support for type conversion.

2. Data processing at the presentation layer

1. for web applications, the presentation layer is mainly used to interact with users, including collecting user input data and presenting the server status to users. Therefore, the data flow at the presentation layer has two main directions: input data and output data.

2. For input data, the conversion from string data to multiple types of data is required. The program cannot be completed automatically. You need to manually convert it in the code.

3. For output data: both java and jsp support direct output of multiple data types.

4. Another data processing layer is: data verification, which is divided into customer verification and server verification. Later, we will focus on

Iii. type conversion

1. All HTTP parameters are strings. The stored data may be string, number, Boolean, date and time, or JavaBean type. Manual type conversion. For example, to convert a string to a Date, use the request. getParameter method to obtain the string; check whether the string is empty; and use the DateFormat. parse method to convert the string to a Date object.

2. Struts2 type conversion

Struts2 built-in type conversion
String and boolean are used to convert the String and boolean values.
Conversion between String and char String and character
String, int, and Integer are converted between strings and integers.
String and Long are used to convert String and Long integer values.
String, double, and Double are used to convert the String and double-precision floating point values.
String and Float are used to convert a String to a single-precision floating point.
String and Date convert the String and Date types. The Date format uses the SHORT format of the Locale where the user request is located.
String and array by default. The array element is a String. If you define a type converter, it can also be another composite data type.
String, Map, List

Struts2 built-in type conversion
String and boolean are used to convert the String and boolean values.
Conversion between String and char String and character
String, int, and Integer are converted between strings and integers.
String and Long are used to convert String and Long integer values.
String, double, and Double are used to convert the String and double-precision floating point values.
String and Float are used to convert a String to a single-precision floating point.
String and Date convert the String and Date types. The Date format uses the SHORT format of the Locale where the user request is located.
String and array by default. The array element is a String. If you define a type converter, it can also be another composite data type.
String, Map, List

3. built-in type conversion

4. Struts type conversion API

The Struts2 type converter is actually implemented based on OGNL. There is an OGNL. TypeConverter interface in the ognl project, which is the interface required to implement the type converter.This interface is defined as follows:

Public interface TypeConverter {
Public Object convertValue (Map arg0, Object arg1, Member arg2, String arg3,
Object arg4, Class arg5 ){
Return null;
}

The preceding TypeConverter must be implemented to implement the type converter, but the methods in the preceding interface are too complex. Therefore, the OGNL project also provides an implementation class for this interface: ognl. defatypetypeconverter, which inherits the class to implement its own type converter. this class is defined as follows:

Public class DefaultTypeConverter extends Object implements TypeConverter {
Public Object convertValue (Map <String, Object> context, Object value, Class toType ){
}
...... // Other methods
}

Functions of the ConvertValue Method
This method completes type conversion, but this type conversion is bidirectional. This method is used to convert strings to object instances, this method is also used to convert an object instance to a string. The type of the toType parameter is the target type to be converted. Therefore, you can determine the conversion direction based on the toType parameter.
ConvertValue method parameters and returned meaning
The first parameter: context is the context of the type conversion environment.
The second parameter: value is the parameter to be converted, and the value varies according to the conversion direction.
The third parameter: toType is the converted target type.
The return value of this method is the value after type conversion. The type of the value also changes with the change of the conversion direction. It can be seen that the convertValue method for conversion accepts the value to be converted. The target type to be converted is a parameter, and then the converted target value is returned.
Why is Value a string array?
For defatypetypeconverter converter, it must take into account the most common situation, so it treats all request parameters as a string array rather than a string. It is equivalent to the parameter value obtained by getParameterValues ().

IV. Implementation of type converter

1. Step 1 registration page

2. Step 2: implement the User encapsulation class

3. Step 3: implement the Action class

5. Step 5: register a type converter using the following methods:

1. Register a local type converter: The local type converter only applies to the attribute of an Action.
2. Register a global converter: The Global converter will take effect for specific attributes of all actions.
3. Use the annotation of JDK to register a type converter: generate a type converter by using the registration method.

6. Register a local Converter
Register the file name format: ActionName-conversion.properties: ActionName is the class name of the Action that requires the converter to take effect, followed by the-conversion. properties string is a fixed part
The preceding file is a typical properties file consisting of key-value pairs. The file content is: propertyName = type converter class.
Below is the content of the UserAction-conversion.properties file:
# To specify the user attribute in UserAction, use the redarmy. user. UserConverter class to convert the type.
User = redarmy. user. UserConverter
Note: The preceding properties file must be in the same package as UserAction.
That is, the above case can be used to achieve local type conversion

7. Global Converter
Registration Name File Format: xwork-conversion.properties file this file is also a properties file, its content is also composed of "composite type = corresponding type converter class.
The contents of the xwork-conversion.properties file are as follows:
# Specify the redarmy. user. User class type converter to redarmy. user. UserConverter
Redarmy. user. User = redarmy. user. UserConverter
Note: The xwork-conversion.properties file must be created under the class folder that is under src

V. Struts2 custom type conversion

The StrutsTypeConverter class is provided in Struts2 to simplify the design of custom type conversion. This class has two abstract methods to implement:

(1) public Object convertFromString (Map context, String [] values, Class toClass );
Processing Method for converting String type data to custom type
Parameters:
Context --- context information related to Action
Values --- the parameter value obtained from the request
ToClass --- target type to be converted

(2) public String convertToString (Map context, Object obj );
Converts a custom type to a String.
Parameters:
Context --- context information related to Action
Obj --- custom type object

Instance analysis: Design and configuration of a date type conversion

(1) design MyDateTypeConverter, inherit StrutsTypeConverter, and overwrite the two methods. The reference code is as follows:
Public Object convertFromString (Map context, String [] values, Class toClass ){
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd ");
Try {
Date v = sdf. parse (values [0]);
Return v;
} Catch (Exception e ){
E. printStackTrace ();
Return new Date ();
}

}

Continued
Public String convertToString (Map context, Object obj ){
SimpleDateFormat sdf = new SimpleDateFormat ("MM dd, yyyy ");
Date v = (Date) obj;
Return sdf. format (v );
}
Although Struts2 supports String and Date conversion by default, it only supports short format and localization-related Date format conversion, which does not necessarily meet your needs. We need to implement our own type conversion.
(2) Add a birthday attribute to the UserInfo class, whose type is java. util. Date.
Public class UserInfo {
Private Integer id;
Private String name;
Private String password;
Private Date birthday;
...
}

(3) configure this type converter for the UserInfo component.
First, create a feature file based on the class name of the UserInfo component. The file name format is class name-conversion. properties.

Like UserInfo-conversion.properties

The file must be in the same package as the UserInfo component.

The content format of this feature file is as follows:
Birthday = demo. converter. MyDateTypeConverter
Note:
Birthday is the property name of the java. util. Date type in the UserInfo component.
Demo. converter. MyDateTypeConverter is the custom conversion implementation class.

The Strus2 framework provides a simple way to handle this problem.

To configure a type converter to a global level, you only need to write a feature file named xwork-conversion.properties that must be located in the/WEB-INF/classes directory with the following content:
Java. util. Date = demo. converter. MyDateTypeConverter

Vi. Custom type converter

Java. util. Date can receive request parameter values in the format. However, if we need to receive Request Parameters in the format of 20091221, we must define the type converter; otherwise, struts2 cannot automatically complete the type conversion.

Import java. util. Date;
Public class HelloWorldAction {
Private Date createtime;

Public Date getCreatetime (){
Return createtime;
}

Public void setCreatetime (Date createtime ){
This. createtime = createtime;
}
}

Public class DateConverter extends DefaultTypeConverter {
@ Override public Object convertValue (Map context, Object value, Class toType ){
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd ");
Try {
If (toType = Date. class) {// when the string is converted to the Date type
String [] params = (String []) value; // Request. getParameterValues ()
Return dateFormat. parse (params [0]);
} Else if (toType = String. class) {// when Date is converted to a String
Date date = (Date) value;
Return dateFormat. format (date );
}
} Catch (ParseException e ){}
Return null;
}
}
Register the above type converter as a local type converter:
Place the ActionClassName-conversion.properties file under the package where the Action class is located, ActionClassName is the class name of the Action, followed by-conversion. properties is a fixed syntax, and for this example, the file name should be a HelloWorldAction-conversion.properties. The content in the properties file is:
Attribute name = full Class Name of the type converter
For this example, the content in the HelloWorldAction-conversion.properties file is:
Createtime = cn. csdn. conversion. DateConverter

Register the above type converter as a global type converter:
Place the WEB-INF file under the xwork-conversion.properties/classes. The content in the properties file is:
Type to be converted = full Class Name of the type converter
For this example, the content in the xwork-conversion.properties file is:
Java. util. Date = cn. csdn. conversion. DateConverter

Java. util. Date can receive request parameter values in the format. However, if we need to receive Request Parameters in the format of 20091221, we must define the type converter; otherwise, struts2 cannot automatically complete the type conversion.

Import java. util. Date;
Public class HelloWorldAction {
Private Date createtime;

Public Date getCreatetime (){
Return createtime;
}

Public void setCreatetime (Date createtime ){
This. createtime = createtime;
}
}

Public class DateConverter extends DefaultTypeConverter {
@ Override public Object convertValue (Map context, Object value, Class toType ){
SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd ");
Try {
If (toType = Date. class) {// when the string is converted to the Date type
String [] params = (String []) value; // Request. getParameterValues ()
Return dateFormat. parse (params [0]);
} Else if (toType = String. class) {// when Date is converted to a String
Date date = (Date) value;
Return dateFormat. format (date );
}
} Catch (ParseException e ){}
Return null;
}
}
Register the above type converter as a local type converter:
Place the ActionClassName-conversion.properties file under the package where the Action class is located, ActionClassName is the class name of the Action, followed by-conversion. properties is a fixed syntax, and for this example, the file name should be a HelloWorldAction-conversion.properties. The content in the properties file is:
Attribute name = full Class Name of the type converter
For this example, the content in the HelloWorldAction-conversion.properties file is:
Createtime = cn. csdn. conversion. DateConverter

Register the above type converter as a global type converter:
Place the WEB-INF file under the xwork-conversion.properties/classes. The content in the properties file is:
Type to be converted = full Class Name of the type converter
For this example, the content in the xwork-conversion.properties file is:
Java. util. Date = cn. csdnconversion. DateConverter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.