struts2中的自定义类型转换器

来源:互联网 发布:python web和java web 编辑:程序博客网 时间:2024/06/05 17:51

自定义类型转换器

自定义一个时间类型的转化器类,类必须继承DefaultTypeConverter,并且重写convertValue方法

public class DateConverter extends DefaultTypeConverter {@Overridepublic Object convertValue(Map<String, Object> context,Object value,Class toType) {      SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");      try {        if(toType==Date.class)        {//从url或表单获取提交的元素可能是复选框的提交,所以需要使用数组来获取           String[] params=(String[])value;              return dateFormat.parse(params[0]);        }        else if(toType==String.class)        {           Date date=(Date)value;           return dateFormat.format(date);        }      } catch (ParseException e) {        e.printStackTrace();      }      return null;   }}

转换器中的方法convertValue是双向的,比如在页面提交的时候参数value为页面的提交或url的参数,toType为需要转换的要类型,这个例子是将string类型转换为Date类型,当要显示到页面的时候value为Date而toType为需要转换的类型为string

将上面的类型转换器注册为局部类型转换器:

在Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassName是Action的类名,后面的-conversion.properties是固定写法。在properties文件中的内容为:

属性名称=类型转换器的全类名


将上面的类型转换器注册为全局类型转换器:

在WEB-INF/classes下或SRC文件夹下放置xwork-conversion.properties文件。在properties文件中的内容为:

待转换的类型=类型转换器的全类名

对于本例而言, xwork-conversion.properties文件中的内容为:

java.util.Date=类型转换器的全类名


原创粉丝点击