struts2自定义全局类型转换器

java.util.Date 类型的属性可以接收格式为 2009-07-20 的请求参数值。但如果我们需要接收格式为 20091221 的请求 参数,我们必须定义类型转换器,否则 struts2 无法自动完成类型转换。
import java.util.Date;
public class HelloWorldAction {
private Date createtime;
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
 
public class DateConverter extends DefaultTypeConverter {
                @Override  public Object convertValue(Map context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if(toType == Date.class){// 当字符串向 Date 类型转换时
String[] params = (String[]) value; // Request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){// Date 转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}
将上面的类型转换器注册为 局部类型转换器
Action 类所在的包下放置 ActionClassName-conversion.properties 文件, ActionClassName Action 的类名,后面的 - conversion.properties 是固定写法,对于本例而言,文件的名称应为 HelloWorldAction-conversion.properties 。在 properties 文件中 的内容为:
属性名称 = 类型转换器的全类名
对于本例而言, HelloWorldAction-conversion.properties 文件中的内容为:
createtime= cn.itcast.conversion.DateConverter
 
将上面的类型转换器注册为全局类型转换器:
WEB-INF/classes 下放置 xwork-conversion.properties 文件 。在 properties 文件中的内 容为:
待转换的类型 = 类型转换器的全类名
对于本例而言, xwork-conversion.properties 文件中的内容为:
java.util.Date = cn.itcast.conversion.DateConverter

猜你喜欢

转载自free0007.iteye.com/blog/1757242