Struts 2自定义类型转换器

来源:互联网 发布:81端口批量入侵摄像头 编辑:程序博客网 时间:2024/04/30 06:25

1:写个类型转换

public class DateTypeConverter extends com.opensymphony.xwork2.conversion.impl.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 (ParseException e) {}
               return null;
     }
}

 

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

 

Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassNameAction的类名,后面的-conversion.properties是固定写法,对于本例而言,文件的名称应为HelloWorldAction-conversion.properties 。在properties文件中的内容为:

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

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

createtime= cn.it.conversion.DateConverter