类型转换器分为全局类型转换器和局部类型转换器。全局类型转换针对所有Action都起作用,而局部类型转换器针对某个Action
一、全局类型转换器。将字符串x,y转换成Point
Login.jsp页面
<s:form method="post" action="test"> <s:textfield name="username" label="账号"></s:textfield> <s:password name="password" label="密码"></s:password> <s:textfield name="point" label="坐标"></s:textfield> <s:submit></s:submit> </s:form>
定义实体类
package models; public class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public Point() { } public Point(int x, int y) { this.x = x; this.y = y; } }
Point.java
package models; public class User { private String username; private String password; private Point point; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } }
User.java
定义Action类
package action; import com.opensymphony.xwork2.ModelDriven; import models.Point; import models.User; public class Test implements ModelDriven<User> { private User user=new User(); public String execute(){ System.out.println(user.getPoint()); return "success"; } public User getModel() { // TODO Auto-generated method stub return user; } }
Test.java
定义类型转换器
package coverter; import java.util.Map; import models.Point; import org.apache.struts2.util.StrutsTypeConverter; public class PointConverter extends StrutsTypeConverter{ @Override public Object convertFromString(Map arg0, String[] arg1, Class arg2) { Point point=null; if(arg1.length>0){ point=new Point(); String[] cods=arg1[0].split(","); point.setX(Integer.parseInt(cods[0])); point.setY(Integer.parseInt(cods[1])); } return point; } @Override public String convertToString(Map arg0, Object arg1) { Point point=(Point)arg1; return point.getX()+","+point.getY(); } }
PointConverter.java
在src下新建一个xwork-conversion.properties文件,内容如下:
models.Point=coverter.PointConverter
前面是需要类型转换的类,后面是转换器
时间: 2024-11-10 14:44:41