1.JAVA类
Action.java
package com.lxitedu.ant;
import com.opensymphony.xwork2.ActionSupport;
public class Action extends ActionSupport {
private static final long serialVersionUID = 1L;
private Vo vo;
public void setVo(Vo vo) {
this.vo = vo;
}
public Vo getVo() {
return vo;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
Vo.java
package com.lxitedu.ant;
import java.sql.Date;
public class Vo {
private String name;
private int age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
2. 转换器
public class UserConverter extends StrutsTypeConverter {
@SuppressWarnings("unchecked")
public Object convertFromString(Map context, String[] values, Class toClass) {
Vo vo = new Vo();
String[] userValues = values[0].split(",");
vo.setName(userValues[0]);
vo.setAge(Integer.parseInt(userValues[1]));
vo.setBirthday(Date.valueOf(userValues[2]));
return vo;
}
@SuppressWarnings("unchecked")
@Override
public String convertToString(Map context, Object o) {
Vo vo=(Vo)o;
return "<"+vo.getName()+","+vo.getAge()+","+vo.getBirthday()+">";
}
}
3.在src目录下定义一个资源文件
xwork-conversion.properties
com.lxitedu.ant.Vo=com.lxitedu.ant.UserConverter
/*包名.类名=包名.转换器*/
4.jsp
index.jsp
<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="abc/vo.action">
<s:textfield name="vo" label="User Name" /><br/>
提示:按照这种格式输出,如:chenmiao,22,1988-5-2
<s:submit/>
</s:form>
</body>
</html>
userInfo.jsp
<%@ 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
姓名:<s:property value="vo.name"/><br/>
年齡:<s:property value="vo.age"/><br/>
生日:<s:date name="vo.birthday" format="yyyy-MM-dd" /><br/>
<s:property value="vo"/><br/>
</body>
</html>
struts.XML
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="hello" namespace="/abc" extends="struts-default"> <action name="vo" class="com.lxitedu.ant.Action"> <result name="success">/userInfo.jsp</result> <result name="input" >/index.jsp</result> </action> </package> </struts>