转帖:http://bolingsky.blog.sohu.com/28316481.html
1.新建Web Project,添加Struts框架
2.新建from,action,jsp
FormBean:
Name:loginForm
type:DynaValidatorForm
添加两个参数:username和userpass
同时创建login.jsp ,Action默认关联
得到配置描述:
<form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="userpass" type="java.lang.String" />
<form-property name="username" type="java.lang.String" />
</form-bean>
...........
<action
attribute="loginForm"
input="/login.jsp"
name="loginForm"
path="/login"
scope="request"
type="org.validate.struts.action.LoginAction" />
3.为action添加 validate="true"属性,表明此action需要使用Validator验证
4.在struts-config.xml中ctrl+n,新建Struts1.2 PlugIn
Plugin class为org.apache.struts.validator.ValidatorPlugIn
添加属性pathnames,值为/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml
5.WEB-INF中新建一xml(Basic Templates)--Create XML file From a DTD file,取名为validation.xml,选择XML Catalog entry,这里我选择了Commons Validator Rules Configuration 1.1.3
编写xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN" "validator_1_1_3.dtd" >
<form-validation>
<formset>
<form name="loginForm">
<field property="username" depends="required">
<arg key="username"/>
<var>
<var-name>mask</var-name>
<var-value>^[a-zA-Z]*$</var-value>
</var>
</field>
</form>
</formset>
</form-validation>
6.同时在资源文件中添加:username=name errors.required={0} required
7.回到先前我们创建的login.jsp
添加其代码到body中:
<html:form action="/login" οnsubmit="return validateLoginForm(this)">
userpass : <html:password property="userpass"/><br/>
username : <html:text property="username"/><html:errors property="username"/><br>
<html:submit/><html:cancel/>
</html:form>
<html:javascript formName="loginForm"/>
8.部署测试
如果username框中不输入内容提交的话,如弹出警告框则说明成功了!(警告框中的内容应该为资源文件中errors.required中定义的!{0}参数值为validation.xml中描述的<arg key="username"/>,然后key="username" 中的username又为资源文件中的username=name
现在思路应该清楚了!