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>标签输出
}