二.第二种struts2类型转换方式实例
1.convert.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>类型转换</title>
</head>
<body>
<form action="convert.action" method="post">
point:<input name="point" type="text">
<input type="submit" value="submit">
</form>
</body>
</html>
2.convertResult.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>类型转换结果页面</title>
</head>
<body>
point:<s:property value="point"/>
</body>
</html>
3.Point.java(POJO类)
package com.hitsoft.model;
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;
}
@Override
public String toString() {
String result = "x = " + x + " , y = " +y;
return result;
}
}
4.struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="convert" class="com.hitsoft.action.ConvertAction">
<result name="success">/convertResult.jsp</result>
</action>
</package>
</struts>
5.ConvertAction.java
package com.hitsoft.action;
import java.util.Date;
import com.hitsoft.model.Point;
import com.opensymphony.xwork2.ActionSupport;
public class ConvertAction 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";
}
}
6.ConvertAction-conversion.properties(必须与ConvertAction类在同一级包下定义)
point=com.hitsoft.convert.PointConverter
7.PointConverter.java
package com.hitsoft.convert;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
import com.hitsoft.model.Point;
public class PointConverter extends StrutsTypeConverter{
@SuppressWarnings("unchecked")
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
Point point = new Point();
String value = values[0];
String[] result = value.split(",");
point.setX(Integer.parseInt(result[0]));
point.setY(Integer.parseInt(result[1]));
return point;
}
@SuppressWarnings("unchecked")
@Override
public String convertToString(Map context, Object o) {
Point point = (Point) o;
int x = point.getX();
int y = point.getY();
String result = "x: " + x + "y:" + y;
return result;
}
}
8.访问地址:
http://localhost:8080/struts2/convert.jsp
输入:
1,2
输出:
point:1,2
说明:这种类型转换不能代码复用,有多个对象转换时就需要编写多个转换器。