在struts2中,对常用的数据类型已经自动进行了类型转换工作。但是对于自定义类型struts2没法去做类型转换工作。需要自定类型转换器来实现类型的转换。
- 该功能的作用:将页面传入的字符串转换为自定义的类型。
类型转换的实现步骤
- web.xml
<!-- struts2的前端控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
- 实体类
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 class PointAction {
private Point point;
//获取页面提交的坐标点
public String execute() {
System.out.println("x="+point.getX()+" : "+"y="+point.getY());
return "success";
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
}
- 新建类型转换器类,继承
StrutsTypeConverter
/*
* 自定义类型转换器
*/
public class PointConverter extends StrutsTypeConverter{
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
String value = values[0];//(2,3)
Point point = new Point();
point.setX(Integer.parseInt(value.substring(1,value.indexOf(","))));
point.setY(Integer.parseInt(value.substring(value.indexOf(",")+1, value.length()-1)));
return point;
}
/*
* 在页面中使用ognl表达式获取值时会调用该方法
*/
@Override
public String convertToString(Map context, Object o) {
System.out.println("将类转换为String");
Point p = (Point)o;
return "("+p.getX()+","+p.getY()+")";
}
}
- 将转换器类和转换类型关联,新建配置文件
xwork-conversion.properties
#要转换的类型=转换器类
com.x.pojo.Point=com.x.converter.PointConverter
- struts.xml
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="add" class="com.x.action.PointAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
- 页面
<body>
<form action="add.action" method="post">
点:<input type="text" name="point"><br>
<input type="submit">
</form>
</body>
成功页面需要使用ognl
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${point.x }<br>
${point.y }<br>
<s:property value="point"/>
</body>
</html>
- 运行