Struts2:类型转换器

网页中的数据都是string类型的,而Action中有很多自定义类型,包括自定义的domain域的JavaBean。

Struts2提供了8种基本数据类型的自动类型转换,其他的类型就需要我们自己来转换了。

实现自定义的类型转换器需要实现TypeConverter接口,或者继承DefaultTypeConverter,或者更方便的继承自StrutsTypeConverter。

public class DateConverter extends DefaultTypeConverter {

                @Override  public Object convertValue(Map context, Object value, Class toType) {

  SimpleDateFormatdateFormat = new SimpleDateFormat("yyyyMMdd");

  try{

  if(toType == Date.class){//当字符串向Date类型转换时

  String[] params = (String[]) value;// Request.getParameterValues()

  returndateFormat.parse(params[0]);

  }elseif(toType == String.class){//Date转换成字符串时

  Date date =(Date) value;

  returndateFormat.format(date);

  }

  }catch (ParseException e) {}

  returnnull;

  }

}

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

Action类所在的包下放置ActionClassName-conversion.properties文件,ActionClassNameAction的类名,

后面的-conversion.properties是固定写法。properties文件中的内容为:属性名称=类型转换器的全类名

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

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

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


你可能感兴趣的:(Struts2:类型转换器)