Therefore, if you want to ensure that the system must correctly convert the Date type, you must write a global type conversion class to perform type conversion between Date and String.
Copy the code code 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") }; //Supports date format for conversion
@Override
public Object convertValue(Map context, Object value, Class toType) {
if (toType == Date.class) { //When the browser submits to the server, convert String to Date
Date date = null;
String dateString = null;
String[] params = (String[])value;
dateString = params[0];//Get the date string
for (DateFormat format : ACCEPT_DATE_FORMATS) {
try {
return format.parse(dateString);//Traverse the supported date formats and convert them
} catch(Exception e) {
continue;
}
}
return null;
}
else if (toType == String.class) { //When the server outputs to the browser, perform Date to String type conversion
Date date = (Date)value;
return new SimpleDateFormat("yyyy-MM-dd").format(date);//The output format is yyyy-MM-dd
}
return null;
}
}
Create the 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 including the namespace.
And then a lot of people are done.
But I haven't succeeded yet, the system reports an error
"ERROR (CommonsLogger.java:27) - Conversion registration error"
"java.lang.ClassNotFoundException: com.great.util.DateConverter"
Failed to register type converter?
After careful inspection, I found that there is an extra space after "java.util.Date=com.great.util.DateConverter"! The truth is revealed. Remove the spaces and run again, success!