在
struts
开发中使用
validator
验证是应该注意的基本问题
首先,在
struts-config.xml
里面最后面的位置加上
<
message-resources
parameter
=
"com.ln.struts.ApplicationResources"
/>
和
<
plug-in
className
=
"org.apache.struts.validator.ValidatorPlugIn"
>
<
set-property
property
=
"pathnames"
value
=
"/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"
/>
</
plug-in
>
其中,
validator-rules.xml
用来定义验证规则,
validation.xm
l
用来设置需要定义的表单项,以及该项要进行何种验证,错误时返回什么信息。
ApplicationResources
则是要显示的错误信息的资源文件。示例如下:
validator-rules.xml
:
<!
DOCTYPE
form-validation
PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_0.dtd"
>
<
form-validation
>
<
global
>
<
validator
name
=
"required"
classname
=
"org.apache.struts.validator.FieldChecks"
method
=
"validateRequired"
methodParams
=
"java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg
=
"errors.required"
>
msg
是针对
"required"
验证失败时,要显示的错误。
</
validator
>
</
global
>
</
form-validation
>
validation.xm
l
:
<
form-validation
>
<
formset
>
<
form
name
=
"testForm"
>
<
field
property
=
"name"
depends
=
"required"
>
<
arg0
key
=
"error.name"
/>
arg0
是针对不同的
property
验证失败时要加上的错误信息
</
field
>
<
field
property
=
"password"
depends
=
"required"
>
<
arg0
key
=
"error.password"
/>
</
field
>
</
form
>
</
formset
>
</
form-validation
>
ApplicationResources.properties
:
# Resources for parameter 'com.ln.struts.ApplicationResources'
# Project P/struts
errors.header=<font color=red>
errors.footer=</font>
error.name=A userName
error.password=A password
errors.required={0} is required
然后在页面上分别用
<
html:errors
property
=
"name"
/>
<
html:errors
property
=
"password"
/>
表示出来就行了。(注意:此处的
property
与
validation.xm
l
里面
field
的
property
值要一致)。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=262778