struts2的类型转换实例 java程序员

首先jsp页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'input.jsp' starting page</title>

  </head>
  
  <body>
   
   <h3><font color="red">使用逗号将点的两个坐标分割开</font></h3>
   
   <s:form action="pointConverter">
   
   <s:textfield name="point" label="point"></s:textfield>
   <s:textfield name="age" label="age"></s:textfield>
   <s:textfield name="username" label="username"></s:textfield>
   <s:textfield name="date" label="birthday"></s:textfield>
   
   <s:submit label="submit"></s:submit>
   
   </s:form>
   
  </body>

</html>



然后是bean层

然后**Action,且对应Action目录下有属性文件告诉Action里的属性值需要用自己写的哪个类型转换文件转换

package com.test.converter;


import java.util.Map;


import ognl.DefaultTypeConverter;


import com.test.bean.Point;


public class PointConverter extends DefaultTypeConverter
{


@Override
public Object convertValue(Map context, Object value, Class toType)
{
if(Point.class == toType)                                             //先是由PointAction-conversion.properties配置文件

{
Point point = new Point();

String[] str = (String[])value;

String[] paramValues = str[0].split(",");

int x = Integer.parseInt(paramValues[0]);
int y = Integer.parseInt(paramValues[1]);

point.setX(x);
point.setY(y);

return point;
}
if(String.class == toType)                                           //在页面上需要显示时候才调用,然后再返回string类型
{
Point point = (Point)value;

int x = point.getX();
int y = point.getY();

String result = "[x=" + x + " , y=" + y + "]";

return result;
}

return null;
}

}

还有全局类型转换配置文件xwork-conversion.properties


原文地址:https://www.cnblogs.com/java20130725/p/3215747.html