1.先说一下流程
1.只需要一个转换类,然后继承struts提供的一个转换类StrutsTypeConverter,重写里面的方法。
2.写一个配置文件,名字为:xwork-conversion.properties。
2.接下给出具体代码
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 DateConverter extends StrutsTypeConverter {
/**
* 生成一个DateFormat类,并给定了时间格式
*/
private DateFormat dateFormat;{
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
/**
* 将String类型的时间转换为Date类型
*/
@Override
public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
if(arg2 == Date.class){
try {
return dateFormat.parse(arg1[0]);
} catch (ParseException e) {
e.printStackTrace();
}
}
return "1965-12-30";
}
/**
* 将Date类型时间转换为String
*/
@Override
public String convertToString(Map arg0, Object arg1) {
if(arg1 instanceof Date){
return dateFormat.format((Date)arg1);
}
return "1965-12-30";
}
}
在xwork-conversion.properties,加入java.util.Date = com.lee.vote_lee.tools.DateConverter
实体类中时间类型要为java.util.Date