Struts2学习3 ---局部类型转换
1. 项目树形图如下:
在昨天的基础上,今天学习了局部类型转换,新增加了几个文件,分别是input.jsp; output.jsp; PointAction.java;
Point.java; PointConverter.java;? PointAction-converter.properties;
?
2.1 input.jsp:
</head> <h3><font color="red">使用逗号将point的两个坐标分隔开</font></h3> <body> <s:form action="pointConverter"> <s:textfield name="username" label="username"></s:textfield> <s:textfield name="point" label="point"></s:textfield> <s:textfield name="date" label="birthday"></s:textfield> <s:textfield name="age" label="age"></s:textfield> <s:submit name="submit"></s:submit> </s:form> </body>
?
2.2 Point.java:
package com.test.bean;public class Point { private int x; private int y;}
?? PS: getter and setter here are omited for save spaces
?
2.3 PointAction.java:
public class PointAction extends ActionSupport {private Point point;private int age;private String username;private Date date; @Overridepublic String execute() throws Exception {// TODO Auto-generated method stubreturn SUCCESS;}}
?为了节省篇幅,上述的各个属性的getter,setter方法就再次省略,但是在真正的项目代码中显然必不可少!?
?
2.4:PointAction-converterProperties
point=com.test.converter.PointConverter
?
2.5: struts.xml:
?
</action> <action name="pointConverter" name="code">public class PointConverter extends DefaultTypeConverter{@Overridepublic Object convertValue(Map context, Object value, Class toType) { if(Point.class == toType)//要转换成的类型叫做Point{Point point=new Point();String[] str= (String[])value;//向下类型转换!!String[] paramValue = str[0].split(",");int x=Integer.parseInt(paramValue[0]);int y=Integer.parseInt(paramValue[1]);point.setX(x);point.setY(y);return point;} 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; }}
?
?
3. 注意事项:3.1 properties文件的建立:
? 在建立类型转换的properties文件的时候,首先要明确,是要转换哪一个Action文件中的那一个变量,从而,在建立属性文件时,此文件的名称必须按照《此ACTION类名+‘-conversion.properties’》的格式,并且建立在此Action所在的包下
? 例如,在上例中,我们是想对PointAction中的Point进行类型转换,所以,我们在PointAction.java所在的包:
com.test.Action包下,建立名字为PointAction-conversion.properties的文件。
?
3.2 PointConverter代码解释:
首先,此类继承了,DefaultTypeConverter类,并且我们重写了 Public Object convertValue(Map context, Object value, Class toType)函数,
其中函数中的参数toType是用来判断,类型转换的方向。
if(Point.class == toType) 表示,要将要转换成Point类型(也就是将客户端传来的String转成Point)
if(String.class==toType) 表示,转换的目标类型为String(也就是将某Object转换成显示在客户端的String类型)
?
String[] str= (String[])value;为什么将Value要看做是一个String的数组,而不看成单一的一个String类型变量,是因为,虽然在Input.jsp文件中,point传回来的只是一个String变量,但是,估计到整个开发的环境如果很庞大的话,难免会有多个叫做Point的空间,会在同一个.jsp文件中,也就是会同一时间有多个Point往服务器传值,所以,写成一个String数组来接受,是有一定道理的(这个部分是结合视频老师中的描述,和自己的猜想得到的,不一定正确,如果有高人发现错误,或者有更精确的见解,欢迎拍砖,指点!)
3.3 整个运作的流程:
1. 首先,用户在客户端的界面上输入 按格式要求的数据。如图:
?
?
?
2.? A.? 在input.jsp文件中,找到Action=“pointConverter”??
???? B.? 然后结合struts.xml文件中的“
<action name="pointConverter" src="/img/2012/09/23/1541516874.png">
?
?
?