在jsp页面提交的都是string类型的
但是在action中,数据类型可以是各种类型
例如int,Date等等 对于这些,struts将会自动进行转化
当用户自定义一个类型时,需要进行自定义类型的转化
以下一个例子:
1.自定义类型 com.test.bean.Point.java
package com.test.bean;
public class Point {
//坐标
private int x;
private int y;
//省略get,set方法,自己加上
}
2.定义一个Action,使用到Point com.test.action.PointAction.java
package com.test.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.Point;
public class PointAction extends ActionSupport {
private Point point;
private int age;
private String username;
private Date date;
public String execute() throws Exception {
return SUCCESS;//直接返回成功
}
}
3.定义对应类型转化类 com.test.converter.PointConverter.java
package com.test.converter;
import java.util.Map;
import com.test.bean.Point;
import ognl.DefaultTypeConverter;
public class PointConverter extends DefaultTypeConverter {
public Object convertValue(Map context, Object value, Class toType) {
//转化为point 从客户端到服务器端输入读取
if(Point.class == toType)
{
Point point = new Point();
String[] str = (String[])value;
//point在输入时用逗号间隔,见input.jsp
String[] xy = str[0].split(",");
//转换
int x = Integer.parseInt(xy[0]);
int y = Integer.parseInt(xy[1]);
point.setX(x);
point.setY(y);
return point;
}
//转化为String 从服务端到客户端输出显示
if(String.class == toType)
{
Point point = (Point)value;
int x = point.getX();
int y = point.getY();
String result="x="+x+" y="+y;
return result;
}
return null;
}
}
4.在 该Action所在包下定义一个properties文件,以标示属性需转化
properties文件名为 Action类名-conversion.properties
以本例 PointAction-conversion.properties
【注意拼写】
其内容为 需转化属性=转化类
本例 point=com.test.converter.PointConverter
【只有一行】
5.配置对应的struts.xml 添加action
<action name="pointCoverter" class="com.test.action.PointAction">
<result name="success">/output.jsp</result>
</action>
6.input.jsp【引入标签,以下只给出body】
<body>
<h3><font color="red">使用逗号将点的坐标隔开 </font></h3>
<s:form action="pointCoverter">
<s:textfield name="point" label="坐标"></s:textfield>
<s:textfield name="age" label="年龄"></s:textfield>
<s:textfield name="date" label="生日"></s:textfield>
<s:textfield name="username" label="姓名"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
</body>
7.output.jsp <%@ taglib prefix="s" uri="/struts-tags" %>
坐标<s:property value="point"/><br>
年龄:<s:property value="age"/><br>
姓名:<s:property value="username"/><br>
生日:<s:property value="date"/><br>
整体流程描述
jsp页面-->struts.xml查找对应action-->
action在对属性point进行set前检测是否有action-conversiong.properties文件-->
有该文件,找到其对应转化类,调用convertValue的方法,根据输出需要类型自动转化-->
转化得到point对象,调用对应set方法-->
执行execute方法,返回SUCCESS-->
output.jsp显示时,有point属性,查找Action的properties文件,调用转化类的转换方法-->
显示结果
切图
![【struts2.0系列3】Struts2自定义类型转换[1] 【struts2.0系列3】Struts2自定义类型转换[1]](https://i-blog.csdnimg.cn/blog_migrate/87b0a5460c4f11ddcfc2f81692056a01.jpeg)
![【struts2.0系列3】Struts2自定义类型转换[1] 【struts2.0系列3】Struts2自定义类型转换[1]](https://i-blog.csdnimg.cn/blog_migrate/90e09e34277b527937e38879b8f53d69.jpeg)