ActionForm的校验
<struts-config> <form-beans> <form-bean name="xxx" type="ActionForm的类全名"> <form-bean name="LoginForm" type="basic.LoginForm"> <!--配置ActionForm类--> </form-beans> <action-mappings> <action path="/basic/login" type="alan.struts.basic.LoginAction" name="xxx" scope="request|sessio(默认值)Form的保存空间"> <forward name="success" path="/basic/success.jsp"/> <forward name="fail" path="/basic/fail.jsp" redirect="false"(重定向,默认false)/> </action> <action-mappings> </struts-config>
ActionForm的校验是struts提供的一项类似于Javascript的表单校验的功能。他可以验证用户填写的表单数据的正确性。
ActionForm的校验,如果表单中的数据符不符合规定格式的要求,ActionForm的validate()方法会返回一个ActionError对象,ActionError对象中封装了一个或多个应用发现的校验错误,每一个错误有一个ActionMessage对象表达,我们可以通过判断这个ActionError的对象是否为空,如果为空那么表单的数据符合格式要求,不为空就是表单项中就有不符合格式要求的项。
struts标签
在使用struts标签的JSP页面中要先加上以下的标签库的引用 <%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %> <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<bean:message key="errors.username.required">这个标签可以从指定的资源文件中根据指定的key值来取得可以对应的值,但是需要在struts-config.xml中进行配置。 配置资源,这些资源可以在ActionMessage中使用,也就是在构造ActionMessage是指定资源文件中的key这样,在发现校验错误时,就可以先在资源文件中指定的key的值了。可以使用struts的<html:errors> <html:message>、<bean:message>标签都可以显示指定错误的消息。 <struts-config> ..... <message-resources parameter="alan.struts.message.MessageResource" /> <!--使用message标签时配置资源文件的位置--> </struts-config>
struts会自动的判断返回ActionError是否为空,如果是空可以自动的转向指定页面,也可以强制不进行校验,虽然可以在Form中不去覆盖validate()方法,但是那样是不可取的。要实现上面提得到功能还需要在struts-config中配置。 <action path="/basic-validate/login" type="alan.struts.basic.LoginAction" name="loginValidateForm" scope="request" validate="true" input="/basic-validate/login.jsp"> <!--scope可以指定Form的存放空间,默认为sessoin--> <!--action标签中配置validate="false"可以不进行校验,input是指定校验出错跳转的页面--> <forward name="success" path="/basic-validate/success.jsp"/> <forward name="fail" path="/basic-validate/fail.jsp"/> </action>
<html:message id="error"><!--id属性是ActionMessage存放在空间中的key--> <h1>${error}</h1> </html:message> <html:errors>标签只会原样输出在ActionErrors中ActionMessage对应资源文件中对应的值。 <html:messages>标签还可以对输出在ActionError中ActionMessage对应资源文件中对应的值作一些显示效果的修改。 <bean:message key="xxx.xxx">标签只会取资源文件中指定key所对应的值,使用bean:message标签可以实现国际化。
struts的html标签
struts的html标签的使用类似于html标签,但是少有区别,指定类型的方式变成使用不同的标签,这样会绑定struts,所以旨在需要时使用。 <html:form method="post" action="/basic-validate/login"> <!-- struts的html标签中的action可以只写转到的actionpath,struts会在解析是自动添加需 要的部分 --> <html:text property="userName" /> <html:password property="password" redisplay="false"/> <!--redisplay="false"不进行回写,只有html:password标签可用--> <html:radio property="hibbos"> <html:submit value="login" /> </html:form>
Struts预定义的Action类
注意:在使用继承Struts预定义的Action类,一定不要覆盖execute方法,否则会导致无法调用自定义Action相应方法。