1. 定义一个类继承自: com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
DateTypeConverter.java
----------------------------------------------------------------------------------------------------
package org.taink.type.converter;
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 DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value,
Class toType) {
DateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if (toType == Date.class) { // 当字符向Date 类型转换时
String[] params = (String[]) value; //request.getParameterValues()
return simpleDateFormat.parse(params[0]);
} else if (toType == String.class) { // 当Date 向字符类型转换时
Date date = (Date) value;
return simpleDateFormat.format(date);
}
} catch (Exception e) {
System.out.println("-----converter date Exception------");
e.printStackTrace();
}
return null;
}
}
2.在src 目录 下创建一个xwork-conversion.properties
xwork-conversion.properties
----------------------------------------------------------
java.util.Date=org.taink.type.converter.DateTypeConverter
3.action 的代码:
EmployeeAction.java
---------------------------------------------------------
package org.taink.struts.action;
import java.util.Date;
public class EmployeeAction {
private Date birthday;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String doAdd() {
return "success";
}
public String execute() {
return "success";
}
}