1.创建一个User.java
package action;
public class User {
private String userName;
private int userAge;
private String userTelephone;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserTelephone() {
return userTelephone;
}
public void setUserTelephone(String userTelephone) {
this.userTelephone = userTelephone;
}
}
2.VisitionAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
public class VisitorAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 7946067185107138837L;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
3.VisitorAction-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<!-- 校验字段 -->
<field name="user">
<!-- 校验器 -->
<field-validator type="visitor">
<!-- 复合类型属性的上下文校验名称 -->
<param name="context">visitorContext</param>
<!-- 校验信息中输入前缀信息 -->
<param name="appendPrefix">true</param>
<message>联系人</message>
</field-validator>
</field>
</validators>
4.User-visitorContext-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<field name="userName">
<field-validator type="requiredstring">
<message>姓名不能为空</message>
</field-validator>
</field>
<field name="userAge">
<field-validator type="int">
<param name="min">10</param>
<param name="max">100</param>
<message>年龄为10-100之间!</message>
</field-validator>
</field>
</validators>
5.struts2.xml
<action name="visitorAction" class="action.VisitorAction">
<result name="success">/success.jsp</result>
<result name="input">/visitor.jsp</result>
</action>
6.visitor.jso
<%@ page language="java" contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>复合类型校验</title>
</head>
<body>
<jsp:include page="index.html"></jsp:include>
<h4>添加联系人</h4>
<p />
<s:form action="visitorAction" method="post">
<s:textfield label="联系人姓名" name="user.userName" />
<s:textfield label="联系人年龄" name="user.userAge" />
<s:textfield label="联系人电话" name="user.userTelephone" />
<s:submit value="提交" />
</s:form>
</body>
</html>