Struts框架中的表单验证与资源文件

1. 配置config.xml
<struts-config>
  <form-beans>
    <form-bean name="myActionForm" type="strutsdemo.MyActionForm" />
  </form-beans>
  <action-mappings>
    <action input="/login.jsp" name="myActionForm" path="/myAction" scope="request" type="strutsdemo.MyAction" validate="true">
      <forward name="ok" path="/ok.jsp" />
      <forward name="oknot" path="/oknot.jsp" />
      <forward name="error" path="/error.jsp" />
    </action>
  </action-mappings>
  <message-resources parameter="StrutsDemo.Application">
  </message-resources>
</struts-config>

<action>中的属性validate="true"指定了激活ActionForm的表单验证;
<message-resources>元素指定资源文件,需要与下一步的web.xml配置文件匹配;

2. 配置web.xml
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>
    <init-param>
      <param-name>application</param-name>
      <param-value>ApplicationResources</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>

<param-name>application</param-name>与第一步的<message-resources>匹配指定资源文件;

3. ActionForm的validate()方法中
     * ActionForm的表单验证,非业务逻辑验证,只对表单数据的合法性进行检查,如非空。
     *
     * 如果validate()方法返回的ActionErrors为null或不包含任何ActionMessage对象或ActionError对象,表示通过验证;
     * Struts框架将ActionForm和HTTP请求一起传给Action的execute();
     * 否则Struts框架将HTTP请求返回到输入的页面中,不会进入到Action的execute()方法,而输入页面即可通过<html:errors>标签来显示错误信息
     *
例:
ActionErrors errors=new ActionErrors();  //定义错误对象,不初始化
    if (userName==null || userName.length()<1 || !userName.equals("uname")){
      errors.add(errors.GLOBAL_ERROR,new ActionError("userNameerror"));//加入到错误容器中
      //userNameerror对应资源文件中的键值对的键,值由<html:errors>标签输出
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值