首页 > 代码库 > Struts2之验证框架二(通过action类名-validation.xml方式)
Struts2之验证框架二(通过action类名-validation.xml方式)
1 index.jsp
<%@ taglib uri="/struts-tags" prefix="s"%>
<body>
<s:form action="ValidateByXML" >
<s:textfield name="username" label="用户名:"></s:textfield><br>
<s:textfield name="password" label="密码::"></s:textfield>
<s:submit name="submit" label="提交" align="center" />
</s:form>
</body>
2action类
package org.action;
import com.opensymphony.xwork2.ActionSupport;
public class ValidationTestAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
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;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.print("输入验证通过");
return SUCCESS;
}
// @Override
// public void validate() {
// // TODO Auto-generated method stub
// if(username==null || username.trim().equals("")){
// addFieldError("username","用户名是必需的!");
// }
// if(password==null || password.trim().equals("")){
// addFieldError("password","密码是必需的!");
// }
// }
}
3action类对应的校验xml文件-ValidationTestAction-validation.xml(命名规则:action类名-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">
<!-- 去空格 -->
<param name="trim">true</param>
<!-- 错误提示信息 -->
<message>用户名是必需的</message>
</field-validator>
</field>
<field name="password">
<!-- 验证字符串不能为空,即必填 -->
<field-validator type="requiredstring">
<!-- 去空格 -->
<param name="trim">true</param>
<!-- 错误提示信息 -->
<message>密码是必需的</message>
</field-validator>
</field>
</validators>
4struts.xml(界面和action的纽带)
<?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="default" extends="struts-default">
<action name="ValidateByXML" class="org.action.ValidationTestAction">
<result name="success" >/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
5运行截图
Struts2之验证框架二(通过action类名-validation.xml方式)