How to solve the struts2 date type conversion, struts2 date type
Therefore, to ensure that the system must convert the Date type correctly, we need to write a global type conversion class to convert the types between Date and String.
Copy codeThe Code is as follows:
Package com. great. util;
Import java. text. DateFormat;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. Map;
Import com. opensymphony. xwork2.conversion. impl. DefaultTypeConverter;
Public class DateConverter extends DefaultTypeConverter {
Private static final DateFormat [] ACCEPT_DATE_FORMATS = {
New SimpleDateFormat ("dd/MM/yyyy "),
New SimpleDateFormat ("yyyy-MM-dd "),
New SimpleDateFormat ("yyyy/MM/dd")}; // Date Format that supports Conversion
@ Override
Public Object convertValue (Map context, Object value, Class toType ){
If (toType = Date. class) {// convert String to Date when the browser submits a request to the server
Date date = null;
String dateString = null;
String [] params = (String []) value;
DateString = params [0]; // obtain the date string
For (DateFormat format: ACCEPT_DATE_FORMATS ){
Try {
Return format. parse (dateString); // supports format and conversion for Traversing dates
} Catch (Exception e ){
Continue;
}
}
Return null;
}
Else if (toType = String. class) {// when the server outputs data to the browser, convert the Date to String type.
Date date = (Date) value;
Return new SimpleDateFormat ("yyyy-MM-dd"). format (date); // The output format is yyyy-MM-dd.
}
Return null;
}
}
Create a xwork-conversion.properties file in the root directory and add the following statement in it to register the type converter
Java. util. Date = com. great. util. DateConverter
Among them, com. great. util. DateConverter is the full name of the date conversion class containing the namespace.
Then many people are done.
I have not succeeded yet, and the system reports an error
"ERROR (CommonsLogger. java: 27)-Conversion registration error"
"Java. lang. ClassNotFoundException: com. great. util. DateConverter"
Failed to register the type converter?
Check carefully and find that there is a space behind "java. util. Date = com. great. util. DateConverter! The truth is clear. Remove spaces and run again. Success!