利用配置文件进行校验主要是增加了一些xml文件来对具体表单中各个字段进行输入校验
<!-- 用户信息注册form表单 --> <s:form action="Register.action" validate="true"> <table width="60%" height="76" border="0"> <!-- 各标签定义 --> <s:textfield name="username" label="用户名"/> <s:password name="password" label="密 码" /> <s:password name="repassword" label="密 码确认" /> <s:textfield name="birthday" label="生日"/> <s:textfield name="mobile" label="手机号码"/> <s:textfield name="age" label="年龄"/> <s:submit value="注册" align="center"/> </table> </s:form>
<?xml version="1.0" encoding="gb2312"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <!—检验用户名的长度 -- > <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">8</param> <message>用户名长度必须在${minLength}-${maxLength}位之间</message> </field-validator> <!—检验用户名是否已输入 -- > <field-validator type="requiredstring"> <message>请输入用户名</message> </field-validator> </field> <field name="password"> <!—检验密码的长度 -- > <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">8</param> <message>密码长度必须在${minLength}-${maxLength}位之间</message> </field-validator> <!—检验密码是否已输入 -- > <field-validator type="requiredstring"> <message>请输入密码</message> </field-validator> </field> <field name="repassword"> <!—检验确认密码的长度 -- > <field-validator type="stringlength"> <param name="minLength">6</param> <param name="maxLength">8</param> <message>确认密码长度必须在${minLength}-${maxLength}位之间</message> </field-validator> <!—检验确认密码是否已输入 -- > <field-validator type="requiredstring"> <message>请输入确认密码</message> </field-validator> <!—检验密码和确认密码的输入内容是否一致 -- > <field-validator type="fieldexpression"> <param name="expression">password==repassword</param> <message>确认密码和密码输入不一致</message> </field-validator> </field> <field name="birthday"> <!—检验生日是否已输入 -- > <field-validator type="required"> <message>请输入生日日期</message> </field-validator> <!—检验输入日期是否在一个有效日期范围内 -- > <field-validator type="date"> <param name="min">1928-01-01</param> <param name="max">2004-01-01</param> <message>输入生日日期无效</message> </field-validator> </field> <field name="mobile"> <!—检验手机号码是否已输入 -- > <field-validator type="requiredstring"> <message>请输入手机号码</message> </field-validator> <!—检验输入手机号码长度是否是11位有效手机号码-- > <field-validator type="stringlength"> <param name="minLength">11</param> <message>请输入正确的手机号码,号码位数必须为11位</message> </field-validator> </field> <field name="age"> <!—检验年龄是否已输入 -- > <field-validator type="required"> <message>请输入年龄</message> </field-validator> <!—检验输入年龄是否符合特定年龄范围 -- > <field-validator type="int"> <param name="min">1</param> <param name="max">80</param> <message>年龄必须在${min}-${max}岁之间</message> </field-validator> </field> </validators>
首先在Action代码中去除所有validate和validateXXX方法的代码。然后在和Action类文件同一级目录下增加XXX-validation.xml配置文件。这里“XXX”是Action类文件名字,表示该XML文件中所有输入校验的规则定义和错误信息显示方式都只针对该Action有效
Struts2输入校验出错信息的国际化配置形式