背景: 对于JSP中的输入项的有效性进行判断,这部分可以以JS前端的判断也可以递交服务器进行验证.为了将这部分解耦,struts做了以下几个方面的处理:
1. 重载ActionSupport类中的validate()方法
2. 新增ActionSupport类中的method,然后在
<action name = "login" class = "com.login.loginAction" method = "login">
将验证的逻辑处理卸载login方法中.
3. 基于Struts2的验证框架的输入检验
public class Struts2yanzheng extends ActionSupport
{
//属性+get+set方法
}
增加Struts2yanzheng-validation.xml作为验证
<validators>
<field name = "user">
<field-validator type = "requiredstring">
<param name ="trim">true</param>
<message>必须输入用户名!</message>
</field>
<field name = "pass">
<param name = "trim">true</param>
<message>必须输入密码</message>
</field>
</validators>
重点是action+validation.xml的配置文件
<field name = "user">
<field-validator type = "regex">
<param name = "expression">
<![CDATA[/w]{4,25}]]>
</param>
<message>xxxx</message>
</field-validator>
</field>
<field name = "username">
<field-validator type = "required">
<message>
xxxxxxxxx
</message>
</field-validator>
</fieldname>
<field name = "password">
<field-validator type ="requiredstring">
<param name= "trim">
true</param>
</field-validator>
<fileld-validator>
</field>
<field name = "age">
<field-validator type= "int">
<param name = "trim">true</param>
<param name = "max">50</param>
<param name = "min">25</param>
</field-validator>
</field>
4. 使用客户端JS验证