About the Struts2 type conversion detailed _java

Source: Internet
Author: User
Tags dateformat locale

The meaning of type conversion

For an intelligent MVC framework, type conversions are unavoidable. Because the request parameters of the B/s (browser/server) structure are sent through the browser to the server, these parameters cannot have a rich data type, so the conversion of the data type must be done on the server side.

The MVC framework is a presentation layer solution that is supposed to provide support for type conversions, and STRUTS2 provides very powerful type conversion support.

Second, the processing of the performance layer data

1. For Web applications, the presentation layer is primarily used to interact with the user, including collecting user input data and rendering the server state to the user. Therefore, the data flow of the presentation layer has two main directions: input data and output data.


2, for input data: You need to complete the conversion from string data to multiple types of data. Programs are usually not automatically completed and need to be manually converted in code


3, for output data: either Java or JSP support a variety of data types of direct output.


4, the performance layer of another data processing is: Data validation, divided into customer checksums and server-side checksum. I'll focus on that.

Third, type conversion

1, HTTP parameters are string types. The saved data may be a string, number, Boolean, datetime, or JavaBean type. Manual type conversions, such as converting a string to a date by: getting a string by using the Request.getparameter method, checking for null, and converting a string to a Date object by the Dateformat.parse method

2. STRUTS2 type Conversion


STRUTS2 Built-in type conversions
The conversion between string and Boolean completion strings and Booleans
String and char the usual conversion between strings and characters
Conversion between string and int, integer completion strings and integral types
Conversion between string and long complete string
String and double, double to complete the conversion of strings and double-precision floating-point values
The conversion between string and float complete strings and single-precision floating-point
The conversion between string and date completion strings and dates, date format using the short format of the locale where the user request is in the format
string and arrays in the default case, the array element is a string, and if the user defines a type converter, it can be another composite data type
string and map, List

STRUTS2 Built-in type conversions
The conversion between string and Boolean completion strings and Booleans
String and char the usual conversion between strings and characters
Conversion between string and int, integer completion strings and integral types
Conversion between string and long complete string
String and double, double to complete the conversion of strings and double-precision floating-point values
The conversion between string and float complete strings and single-precision floating-point
The conversion between string and date completion strings and dates, date format using the short format of the locale where the user request is in the format
string and arrays in the default case, the array element is a string, and if the user defines a type converter, it can be another composite data type
string and map, List

3. Built-in type conversion

4. Struts Type Conversion API

The Struts2 type converter is actually implemented based on OGNL, and there is a Ognl.typeconverter interface in the OGNL project that implements the interface that the type converter must implement. 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;
}

The implementation type converter must implement the above TypeConverter, but the method in the above interface is too complex, so the OGNL project also provides an interface implementation class: Ognl.defaulttypeconverter, Implement your own type converter by inheriting the class. The 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
}

The role of Convertvalue method
This method completes the type conversion, but this type conversion is bidirectional and is implemented through this method when converting the string to an object instance, and when the object instance is converted to a string. 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 judged according to the ToType parameters.
Convertvalue method parameters and return meaning
The first argument: context is the contexts of the type transformation environment
The second parameter: value is the parameter that needs to be converted, depending on the value of the different value parameters of the conversion direction.
Third parameter: ToType is the converted target type
The return value of the method is the value after the type conversion. The type of the value will also change as the direction of the transformation changes. This shows that the Convertvalue method of conversion 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 scenarios, so he treats all request parameters as string arrays rather than strings. Equivalent to Getparametervalues () parameter value obtained

Iv. Implementation of type converter

1, the first step registration page

2. The second step: Implement User encapsulation Class

3. Step three: Implement Action class

5, Step Five: the implementation of the type converter registration, the registration method has the following three kinds:


1. Register the local type converter: The local type converter functions only on the properties of an action
2. Register the Global type converter: The global type Converter will take effect for all action specific properties
3. Use JDK1.5 annotation to register type converters: Generate type converters by registering

6. Local type converter Registration
Registration file name format: Actionname-conversion.properties:actionname is the class name of the action that requires the converter to take effect, and the following-conversion.properties string is a fixed part
The above file is a typical properties file, the file is composed of Key-value. File contents: Propertyname= type converter class
The following is the contents of the Useraction-conversion.properties file:
#指定UserAction中的user属性需要使用redarmy. User.userconverter class Complete type conversion
User=redarmy.user.userconverter
Note: The above properties file must be in the same package with Useraction
That is, the above case can be used to implement the local type conversion

7. Global type converter
File format for Registered name: Xwork-conversion.properties File The file is also a properties file, and its contents are made up of the "composite type = corresponding type converter class" item.
The following are the contents of the Xwork-conversion.properties file:
The type converter for the #指定所有redarmy. User.user class is Redarmy.user.UserConverter
Redarmy.user.user=redarmy.user.userconverter
Note: The xwork-conversion.properties file must be created under the class folder that is underneath SRC

Five, Struts2 custom type conversions

The Strutstypeconverter class is provided in Struts2 to simplify the design of custom type conversions, which have two abstract methods that need to be implemented:

(1) Public Object convertfromstring (Map context, string[] values, Class toclass);
Handling methods for converting string data to a custom type
Parameters:
Context---Contextual information related to action
Values---The value of the parameter obtained from the request
Toclass---Type of target to convert

(2) Public String converttostring (Map context, Object obj);
For custom type conversion to string
Parameters:
Context---Contextual information related to action
Obj---The Custom type Object

Example analysis: Design and configuration of a date type conversion

(1) design mydatetypeconverter, inherit Strutstypeconverter, overwrite two of these 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 mm month DD day");
Date v = (date) obj;
return Sdf.format (v);
}
Although Struts2 can support string and date conversions by default, only short and localized date format conversions are supported, and we need to implement our own type conversions, not necessarily in line with our own needs.
(2) Add a birthday property for the UserInfo class, which is of type java.util.Date
public class UserInfo {
Private Integer ID;
private String name;
private String password;
Private Date birthday;
...
}

(3) Configure the type converter for userinfo this component
First, you create an attribute file based on the class name of the UserInfo component, and the file name format is the class name-conversion.properties

Like Userinfo-conversion.properties.

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

The attribute file content is formatted as follows:
Birthday=demo.converter.mydatetypeconverter
Description
Birthday is the property name of the Java.util.Date type in the UserInfo component
Demo.converter.MyDateTypeConverter implementation classes for custom transformations

The STRUS2 framework provides a simple way to deal with this.

To configure a type converter as a global level, simply write an attribute file named Xwork-conversion.properties, which must be located in the/web-inf/classes directory, as follows:
Java.util.date=demo.converter.mydatetypeconverter

Vi. Custom Type Converters

Properties of the Java.util.Date type can receive request parameter values formatted as 2009-07-20. But if we need to receive a request parameter with a 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 the 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 the-conversion.properties is fixed, for this example, the file The name should be helloworldaction-conversion.properties. The content in the properties file is:
Attribute name = Full class name of 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 content in the properties file is:
Type to convert = Full class name of type converter
For this example, the contents of the Xwork-conversion.properties file are:
Java.util.date= Cn.csdn.conversion.DateConverter

Properties of the Java.util.Date type can receive request parameter values formatted as 2009-07-20. But if we need to receive a request parameter with a 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 the 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 the-conversion.properties is fixed, for this example, the file The name should be helloworldaction-conversion.properties. The content in the properties file is:
Attribute name = Full class name of 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 content in the properties file is:
Type to convert = Full class name of type converter
For this example, the contents of the Xwork-conversion.properties file are:
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.