struts2 类型转换

来源:互联网 发布:三七灰土白灰用量算法 编辑:程序博客网 时间:2024/04/18 15:59

  首先struts2框架在接收客户端发过来的信息(全部以字符串的形式)会自动转化为action类中定义的变量所定义的类型,如果不能转换struts2框架会自动查找与该action类名相对应的一个properties文件,在此文件里会找到相对应对的类型转化类。

 

   此类由程序员自己定义并继承DefaultTypeConveter,并实现conveterValue方法,在此方法中

public Object convertValue(Map context, Object value, Class toType) {
  //Client data to Server
  if (Point.class == toType){
   Point point = new Point();
   
   String[] str = (String[])value;
   
   String[] paramValues = str[0].split(",");
   put("str[0]="+str[0]);
   int x = Integer.parseInt(paramValues[0]);
   int y = Integer.parseInt(paramValues[1]);
   
   put("x="+x  + " y="+y);
   
   return point;   
  }
  //Server to Client
  if (String.class == toType){
   Point point = new Point();
   String result = "[x=" + point.getX() + ",y=" + point.getY() + "]";
   //String result = "[x=11,y=50]"; //打开该注释之后,数据可以输出到output.jsp中
   put("result="+result);
   return result;
  }
  return null;
}