1 、自定义局部类型转换器步骤
定义一个类继承DefaultTypeConverter,并复写方法:
public Object convertValue(Map<String, Object> context, Object value,
Class toType)
例如:
public class DateTypeConverter extends DefaultTypeConverter { @Override public Object convertValue(Map<String, Object> 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 (Exception e) { return null; } return null; } } |
DataAction.java类代码
package net.cjava.action; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; public class DateAction extends ActionSupport { private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String execute() throws Exception { return SUCCESS; } } |
2、配置自定义类型转换器
在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法。
对于本例而言,文件的名称应为DateAction-conversion.properties 。在properties文件中的内容为:
属性名称(Action中属性名称如:date)=类型转换器的全类名
对于本例而言, DateAction-conversion.properties文件中的内容为:
date= net.cjava.action.conversion.DateTypeConverter
3、配置全局类型转换器
将上面的类型转换器注册为全局类型转换器:
在WEB-INF/classes下放置xwork-conversion.properties文件 。在properties文件中的内容为:
待转换的类型=类型转换器的全类名
对于本例而言, xwork-conversion.properties文件中的内容为:
java.util.Date= net.cjava.action.conversion.DateTypeConverter
声明:其它文件不在这里列出来,只把主要的累出来。