[struts]使用struts验证框架验证表单输入如何配置Action

使用struts校验框架验证表单输入很方便,有两种使用方式:1.添加到Action类的validate方法验证用户的输入。2.使用XML表单验证Form Validation Using XML(当然也可以用注释annotation但和xml类似)。原理是一样的,这里以第一种方式说明struts校验框架执行的时机。

struts校验框架执行时机

原文:When the user presses the submit button on the register form, Struts 2 will transfer the user's input to the personBean's instance fields. Then Struts 2 will automatically execute the validate method. If any of the if statements are true, Struts 2 will call its addFieldError method (which our Action class inherited by extending ActionSupport).

If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return "input" as the result of calling the action.

当用户填写完表单并提交时,struts首先将请求数据封装到一个personBean实例的各个数据域中(注意这里自动执行 数据类型转换,struts的优点之一),并作为参数传递给相应action处理类(有的书上称这个也是IOC,把参数注入到action实例中)。然后,执行validate方法验证输入数据是否合法,如果不合法,第一种方式,通过手动调用addFieldError()继承自ActionSupport,添加错误信息。第二种方式,自动调用此方法添加fieldError错误信息。

如果出现任何错误(类型转换、表单输入验证),struts将不再调用execute方法,而是直接调用input方法返回input视图。

错误信息的显示:

So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the register.jsp. Since we used Struts 2 form tags, automatically Struts 2 will add the error messages.

will cause the message "First name is required" to be displayed above the firstName field on the form.

如果表单使用struts标签,且struts.ui.theme不是"simple" 默认是“xhtml”,且返回到注册页面时,相应输入错误的表单域上方就会有提示信息。

如果表单未使用struts标签,或struts.ui.theme是"simple",则需要在页面添加

<s:if test="hasFieldErrors()">
    <s:fielderror/>
</s:if>

或<s:fielderror/>即可。

 

上一篇文章中,提到了action配置时使用验证框架出现问题。校验框架使用的freemarker获取不到key。原因不是首次进入未曾填写注册页,获取不到表单信息。

对于使用struts验证框架时action的配置需要注意:(使用XML表单验证)

1.不配置action处理类,则不会应用action处理类的相应校验规则

<action name="userInfo_login">
            <result>/WEB-INF/view/user/login.jsp</result>
</action>

2.配置action处理类,则xml校验文件命名:类名-validate.xml 或者 类名-action名-validate.xml

posted @ 2012-10-07 19:31  wanpp590  阅读(393)  评论(0编辑  收藏  举报