struts2局部类型转换
需求为:在页面的文本框输入一个x、y坐标,之间用","隔开,Action中有一个Point类型的属性,Point类里面有两个字段,分别是 x,y,int型,要求当页面提交时将文本框中的字符串转换成Point对象,当Action返回到页面时将Point转换成字符串显示
1、首先做一个jsp用于输入和提交:point.jsp
<s:form action="Converter"><s:textfield name="point" label="Point"></s:textfield>
<s:textfield name="point.x" label="Point.X"></s:textfield>
<s:textfield name="point.y" label="Point.Y"></s:textfield>
<s:submit label="submit"></s:submit>
</s:form>
2、再建一个用于显示的jsp-converter.jsp
<body><s:property value="point"/><br>
<s:property value="point.x"/><br>
<s:property value="point.y"/><br>
</body>
3、Action类 ConverterAction
public class ConverterAction extends ActionSupport{private Point point;
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public String execute()throws Exception {
return "success";
}
}
4、struts.xml
<action name="Converter"class="com.test.struts2.action.ConverterAction">
<result name="success">/converter.jsp</result>
<result name="input">/point.jsp</result>
</action>
5、转换类 ConverterPoint
public class ConverterPoint extends DefaultTypeConverter {@Override
public Object convertValue(Map context, Object value, Class toType) {
if(Point.class == toType){
String[] params = (String[])value;
params = params[0].split(",");
Point point = new Point();
point.setX(Integer.parseInt(params[0]));
point.setY(Integer.parseInt(params[1]));
return point;
}else if(String.class == toType){
Point point = (Point)value;
return "x=" + point.getX() + ",y=" + point.getY();
}
return super.convertValue(context, value, toType);
}
}
6、配置转换
在ConverterAction 类的同一目录下定义属性文件ConverterAction-conversion.properties,注意文件 名,-conversion.properties为固定不变,ConverterAction为Action的名字,文件内容:
point=com.test.struts2.action.ConverterPoint
Ok了,这样就完工了
没有评论:
发表评论