Struts2 type conversion & date
The basic types in Struts can be converted by struts's default type converter .. the default format of the day type is February 03, 1992. If we enter January 1, the name will report an error... so we need to convert the type...
1. Local type converter:
Development steps:
(1) Write A type converter to inherit the StrutsTypeConverter class.
(2) Write a configuration file and ActionName-conversion.properties under the same directory of the class to be converted, as I want to convert here is the date type in the UserAction class...
(3) In this configuration file, write the attribute to be converted = the full name of the type converter.
User. date = cn. itcast. converter. MyConverter
2. Global type converter
(1) Write A type converter to inherit the StrutsTypeConverter class
(2) Write a configuration file named xwork-conversion.properties under src
(3) content:
Java. util. Date = cn. itcast. converter. MyConverter
Registry form: (struts configuration file omitted)
Custom type converter:
Package cn. itcast. converter; import java. text. dateFormat; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; import java. util. map; import org. apache. struts2.util. strutsTypeConverter; public class MyConverter extends StrutsTypeConverter {@ Overridepublic Object convertFromString (Map context, String [] values, Class toClass) {DateFormat [] df = {new SimpleDateFormat (yyyy-MM -Dd), new SimpleDateFormat (MM dd, yyyy), new SimpleDateFormat (yyyyMMdd)}; // determines whether it is nullif (values = null | values. length = 0) {return null;} // determines if it is of the Date type if (Date. class! = ToClass) {return null;} for (int I = 0; I
UserAction: to convert to the user. date attribute in this class
package cn.itcast.type;import cn.itcast.domain.User;import com.opensymphony.xwork2.ActionSupport;public class UserAction extends ActionSupport{private User user;public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String register(){System.out.println(user.getUsername()+==+user.getAge()+==+user.getDate());return register;}}If it is: local configuration file:
User. date = cn. itcast. converter. MyConverter
If it is: global configuration file
Java. util. Date = cn. itcast. converter. MyConverter
Enter the following content in the form:
Console printing:
Li Weikang = 22 = Sat Sep 12 00:00:00 CST 1992