1. The meaning of type conversion
For a smart MVC framework, it is inevitable to implement type conversion. Because the request parameters of B/S (browser/server) structure applications are sent to the server through the browser, these parameters cannot have rich data types. , so data type conversion must be completed on the server side
The MVC framework is a presentation layer solution and should provide type conversion support. Struts2 provides very powerful type conversion support.
2. Processing of presentation layer data
1. For web applications, the presentation layer is mainly used to interact with users, including collecting user input data and presenting the status of the server to users. Therefore, the data flow in the presentation layer mainly has two directions: input data and output data.
2. For input data: it is necessary to complete the conversion from string data to multiple types of data. The program usually cannot be completed automatically and needs to be converted manually in the code.
3. For output data: Both java and jsp support direct output of multiple data types.
4. Another data processing in the presentation layer is: data verification, which is divided into client verification and server-side verification. This will be explained in detail later.
3. Type conversion
1. HTTP parameters are all string types. The saved data may be string, number, Boolean, date and time, etc. or JavaBean type. Manual type conversion, such as converting a string to a date, by: obtaining the string through the request.getParameter method; checking whether it is empty; converting the string into a Date object through the DateFormat.parse method
2. Struts2 type conversion
Struts2 built-in type conversion
String and boolean complete the conversion between string and Boolean values
String and char conversion between ordinary strings and characters
String, int, and Integer complete the conversion between strings and integers.
String and Long complete the conversion between string and long integer values
String, double, and Double complete the conversion of strings and double-precision floating point values.
String and Float complete the conversion between strings and single-precision floating point
String and Date complete the conversion between string and date types. The date format uses the SHORT format of the Locale where the user requests the format.
String and array In the default case, the array element is a string. If the user defines a type converter, it can also be other composite data types.
String and Map and List
Struts2 built-in type conversion
String and boolean complete the conversion between string and Boolean values
String and char conversion between ordinary strings and characters
String, int, and Integer complete the conversion between strings and integers.
String and Long complete the conversion between string and long integer values
String, double, and Double complete the conversion of strings and double-precision floating point values.
String and Float complete the conversion between strings and single-precision floating point
String and Date complete the conversion between string and date types. The date format uses the SHORT format of the Locale where the user requests the format.
String and array In the default case, the array element is a string. If the user defines a type converter, it can also be other composite data types.
String and Map and List
3. Built-in type conversion
4. Struts type conversion API
The type converter of Struts2 is actually implemented based on OGNL. There is an ognl.TypeConverter interface in the OGNL project. This interface is the interface that must be implemented to implement the type converter. The 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;
}
To implement a type converter, you must implement the TypeConverter above. However, the methods in the above interface are too complicated, so the OGNL project also provides an implementation class of this interface: ognl.DefaultTypeConverter. You can implement your own type converter by inheriting this class. The class is defined as follows :
public class DefaultTypeConverter extends Object implements TypeConverter{
public Object convertValue(Map<String,Object>context, Objectvalue, ClasstoType) {
}
……//Other methods
}
The role of the ConvertValue method is to complete type conversion, but this type conversion is bidirectional. When a string needs to be converted into an object instance, this method is used. When an object instance is converted into a string, this method is also used. This conversion is done through the toType parameter type which is the target type that needs to be converted. Therefore, the conversion direction can be determined based on the toType parameter.
ConvertValue method parameters and return meaning The first parameter: context is the context of the type conversion environment. The second parameter: value is the parameter that needs to be converted. The value of the value parameter is also different depending on 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 direction of the conversion. It can be seen that the converted convertValue method accepts the value that needs to be converted, the target type that needs to be converted is a parameter, and then returns the converted target value.
Why is Value a string array?
For the DefaultTypeConverter converter, it must take into account the most common situation, so it treats all request parameters as string arrays instead of strings. Equivalent to the parameter values obtained by getParameterValues()
4. Implementation of type converter
1. First step registration page
2. The second step: Implement the User encapsulation class
3. The third step: Implement the Action class
5. Step 5: Register the type converter. There are three registration methods:
1. Register a local type converter: the local type converter only works on the properties of a certain Action
2. Register a global type converter: The global type converter will take effect on all specific attributes of Action.
3. Use JDK1.5 annotations to register the type converter: generate the type converter through registration.
6. Partial type converter registration registration file name format: ActionName-conversion.properties: ActionName is the class name of the Action that needs the converter to take effect, and the following -conversion.properties string is a typical properties file when fixing part or more of the file. It consists of key-value pairs. The content of the file is: propertyName = type converter class. The following is the content of the UserAction-conversion.properties file:
#Specify that the user attribute in UserAction needs to use the redarmy.user.UserConverter class to complete type conversion
user=redarmy.user.UserConverter
Note: The above properties file must be in the same package as UserAction. That is, in the above case, the above method can be used to achieve local type conversion.
7. The file format of the global type converter registration name: xwork-conversion.properties file. This file is also a properties file, and its content is also composed of the "composite type = corresponding type converter class" item.
The following is the content of the xwork-conversion.properties file:
#Specify the type converter of all redarmy.user.User classes as 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.
5. 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 that need to be implemented:
(1) public Object convertFromString(Map context, String[] values, Class toClass);
Processing method parameters used to convert String type data into custom types:
context --- contextual information related to Action
values --- parameter values obtained from the request
toClass --- the target type to be converted
(2) public String convertToString(Map context, Object obj);
Used to convert custom types into String
parameter:
context --- contextual information related to Action
obj --- custom type object
Example analysis: Design and configuration of a date type conversion
(1) Design MyDateTypeConverter, inherit StrutsTypeConverter, and cover two of its 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("yyyy year MM month dd day");
Date v = (Date)obj;
return sdf.format(v);
}
Although Struts2 supports String and Date conversion by default, it only supports short format and localized date format conversion, which may not 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 the type converter for the UserInfo component. First, create a properties file based on the class name of the UserInfo component. The file naming format is class name-conversion.properties.
For example UserInfo-conversion.properties
This 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
illustrate:
birthday is the attribute name of java.util.Date type in the UserInfo component
demo.converter.MyDateTypeConverter is a custom conversion implementation class
The Strus2 framework takes this into account and provides a simple way to handle it.
To configure the type converter at the global level, just write a properties file named xwork-conversion.properties, which must be located in the /WEB-INF/classes directory, with the following content:
java.util.Date=demo.converter.MyDateTypeConverter
6. Custom type converter
Properties of type java.util.Date can receive request parameter values in the format of 2009-07-20. But if we need to receive request parameters in the format of 20091221, we must define a 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 Date type
String[] params = (String[]) value;// Request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//When Date is converted into 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 Action, and the following -conversion.properties is a fixed writing method. For this example, the name of the file should be HelloWorldAction-conversion.properties. The contents in the properties file are:
Property name = Full class name of the type converter For this example, the contents of the HelloWorldAction-conversion.properties file are:
createtime= cn.csdn.conversion.DateConverter
Register the above type converter as a global type converter:
Place the xwork-conversion.properties file under WEB-INF/classes. The contents in the properties file are:
The type to be converted = the fully qualified class name of the type converter. For this example, the contents of the xwork-conversion.properties file are:
java.util.Date= cn.csdn.conversion.DateConverter
Properties of type java.util.Date can receive request parameter values in the format of 2009-07-20. But if we need to receive request parameters in the format of 20091221, we must define a 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 Date type
String[] params = (String[]) value;// Request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//When Date is converted into 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 Action, and the following -conversion.properties is a fixed writing method. For this example, the name of the file should be HelloWorldAction-conversion.properties. The contents in the properties file are:
Property name = Full class name of the type converter For this example, the contents of the HelloWorldAction-conversion.properties file are:
createtime= cn.csdn.conversion.DateConverter
Register the above type converter as a global type converter:
Place the xwork-conversion.properties file under WEB-INF/classes. The contents in the properties file are:
The type to be converted = the fully qualified class name of the type converter. For this example, the contents of the xwork-conversion.properties file are:
java.util.Date= cn.csdnconversion.DateConverter