How to solve struts2 date type conversion
- 2020-04-01 01:36:08
- OfStack
Therefore, in order to ensure that the system must correctly cast the Date type, it is necessary to write a global type casting class to cast between Date and String.
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 converted date formats
@Override
public Object convertValue(Map context, Object value, Class toType) {
if (toType == Date.class) { //String to Date is converted when the browser submits to the server
Date date = null;
String dateString = null;
String[] params = (String[])value;
dateString = params[0];//Gets a string of dates
for (DateFormat format : ACCEPT_DATE_FORMATS) {
try {
return format.parse(dateString);//Traversing the date supports formatting for conversion
} catch(Exception e) {
continue;
}
}
return null;
}
else if (toType == String.class) { //When the server outputs to the browser, it casts Date to String
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 to register the type converter
Java. Util. Date = com. Great. Util. DateConverter
The com. Great. Util. DateConverter is date conversion class contains the full name of the namespace.
And then a lot of people are done.
And 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?
A closer inspection found "Java. Util. Date = com. Great. Util. DateConverter" more behind a space! The truth is out. Remove the space, run again, success!