Struts ActionForm的表单验证功能

1、在struts-config.xml中设置form-bean标签与Action标签的name属性为”userLoginForm”validate属性设为true(可省,默认为true)。设置消息资源参数parameter="com.hwx.struts.ApplicationResources"

struts-config.xml

………

<form-bean name="userLoginForm" type="com.hwx.struts.form.UserLoginForm" />

…....

    <action

      attribute="userLoginForm"

      input="/userLogin.jsp"

      name="userLoginForm"

      path="/userLogin"

      scope="request"

      type="com.hwx.struts.action.UserLoginAction">

      <forward name="success" path="/successLogin.jsp" />

      <forward name="failure" path="/userLogin.jsp" />

</action>

……….

  <message-resources parameter="com.hwx.struts.ApplicationResources" />

 

 

 

2、在包com.hwx.struts下建立消息资源文件ApplicationResources. properties,也就是与struts-config.xml中的message-resources标签设置对应。

ApplicationResources.properties

………

null.error=can not be null

 

 

3、编辑UserLoginForm.javavalidate方法,代码如下:

UserLoginForm.java

………

    public ActionErrors validate(ActionMapping mapping,

            HttpServletRequest request) {

        ActionErrors errors=new ActionErrors();

        if(userName==null || userName.length()<1)

        {

            errors.add("userName", new ActionMessage("null.error"));

        }

        System.out.println("Username = " + userName + "   " + "Password = "+ password );

        return errors;

    }

说明:

errors.add("userName", new ActionMessage("null.error"));

                                      

①与jsp文件中的<html:errors/>标签中的property属性对应,如下:

 

userLogin.jsp

………

<html:errors property="userName"/>

 

       userLogin.jspstruts-config.xml文件中的input="/userLogin.jsp"对应。

②与ApplicationResources. properties中的消息文本设置对应。

 

注意事项:

       web应用在启动时把消息资源文件的内容保存在内存,如果修改了消息资源文件必须重启web应用,这样修改的内容才能在以后的访问中反映出来。

       validate方法主要用于格式与语法的检查,业务逻辑检查在Ation中检查。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值