Struts2- Validation校验类型和配置方法说明
从Struts2 校验框架在验证的场所上可以分为:客户端校验和服务端校验。
???客户端校验是指,在HTML画面上自动生成JavaScript校验代码,在用户提交到服务器之前在客户端浏览器中进行校验。默认位客户端校验。
???服务端校验是指,在数据提交到服务器上之后,在Action处理之前,对客户但提交的数据进行校验。
?
从Struts2校验框架的配置上可以分为:Java Annotation配置和XML配置文件配置
??? JavaAnnotation配置是指,使用Java Annotation语法,在Java源代码上标记需要校验的内容,和校验的方式。
???XML配置文件配置是指,使用XML配置文件配置需要校验的内容和校验方式。
?
5.2节:Validator与Validation
Validation指校验,Validator指谁来校验。
在Struts2框架中Validator必须在系统中注册,如果没有注册,系统使用默认的注册,这些validator注册文件在xwork的jar文件中,内容如下:
<validators>
???<validator name="required"class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
???<validator name="requiredstring"class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
???<validator name="int"class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
???<validator name="double"class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
???<validator name="date"class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
???<validator name="expression"class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
???<validator name="fieldexpression"class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
???<validator name="email"class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
???<validator name="url"class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
???<validator name="visitor"class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
???<validator name="conversion"class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
???<validator name="stringlength"class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
???<validator name="regex"class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
</validators>
?
自己需要注册自己的Validator时,可以使用上述相似的内容,这个文件需要放在WEB-INF/classes目录下,文件的名字叫validators.xml。
?
一旦自己定义了validators.xml文件,系统就不会在加载默认的Validators文件,所以在Validators.xml中需要拷贝默认的内容。
?
5.3节:Validation与Intercepter
Validation使用名字叫做validator的Intercepter,在默认情况下,struts2已经定义了这个Intercepter,我们在不加声明的情况下就可以使用Validation了。
?
5.4节:使用Java Annotation配置校验
importcom.opensymphony.xwork2.validator.annotations包提供了一些必要的Annotation用来配置校验信息。
这些内容包括:
枚举类型
ValidatorType?????
Field???校验字段
Simple?? 校验其他
Annotation(标注)类型
Validation
???用来标记一个类需要被校验
ConversionErrorFieldValidator
???字段转换出错
DateRangeFieldValidator
???日期范围校验
DoubleRangeFieldValidator
???Double类型范围校验
EmailValidator
???Email地址校验
ExpressionValidator
???使用一个OGNL表达式的校验,功能非常强大
FieldExpressionValidator
???针对一个字段的使用OGNL表达式的校验
IntRangeFieldValidator
???Int类型范围校验
RegexFieldValidator
???正则表达式校验
RequiredFieldValidator
???必填字段校验
RequiredStringValidator
???必填String校验,
StringLengthFieldValidator
???字符串长度校验
UrlValidator
??? URL校验
Validations
???可以组合上述的各种校验类型以满足更多的需求。
VisitorFieldValidator
???可以将Action中的对象的属性的校验方法定位到已经定义的对象原有的校验方法
?
CustomValidator
ValidationParameter
???????两个类一起完成自定义的校验
?
示例:
package com.jpleasure;
?
import com.opensymphony.xwork2.ActionSupport;
importcom.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
importcom.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
importcom.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
importcom.opensymphony.xwork2.validator.annotations.Validation;
importcom.opensymphony.xwork2.validator.annotations.ValidatorType;
?
@Validation()
public class RegisterAction extends ActionSupport {
??? privateString name;
??? privateString password;
??? privateString rePassword;
??? privateString mail;
??? privateString description;
?
??? publicString getName() {
???????return name;
??? }
?
???@RequiredFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "name is required")
??? publicvoid setName(String name) {
???????this.name = name;
??? }
?
??? publicString getPassword() {
???????return password;
??? }
?
???@RequiredFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "password is required")
???@StringLengthFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "password must has properlegnth",
???????????minLength = "5", maxLength = "12")
??? publicvoid setPassword(String password) {
???????this.password = password;
??? }
?
??? publicString getRePassword() {
???????return rePassword;
??? }
?
???@RequiredFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true,
???????????message = "input password again please!")
???@StringLengthFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "password must has properlegnth",
???????????minLength = "5", maxLength = "12")
???@FieldExpressionValidator(expression = "password eqrePassword",
???????????message = "two password must match")
??? publicvoid setRePassword(String rePassword) {
???????this.rePassword = rePassword;
??? }
?
??? publicString getMail() {
???????return mail;
??? }
?
???@RequiredFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "mail is required")
??? publicvoid setMail(String mail) {
???????this.mail = mail;
??? }
?
??? publicString getDescription() {
???????return description;
??? }
?
???@RequiredFieldValidator(type = ValidatorType.FIELD,
???????????shortCircuit = true, message = "description is required")
??? publicvoid setDescription(String description) {
???????this.description = description;
??? }
?
??? publicString execute() throws Exception {
?
???????return SUCCESS;
??? }
}
?
5.5节:使用XML配置Validation
Xml配置文件与Action的关系为:
SomeAction.java – SomeAction-validation.xml
且与SomeAction.class处在相同的目录中。
SimpleAction-validation.xml文件示例:
?
<!DOCTYPE validators PUBLIC "-//OpenSymphonyGroup//XWork Validator 1.0.2//EN"
??????"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
? <fieldname="bar">
?????<field-validator type="required">
?????????<message>You must enter a value forbar.</message>
?????</field-validator>
?????<field-validator type="int">
?????????<paramname="min">6</param>
?????????<paramname="max">10</param>
?????????<message>
bar must be between ${min} and ${max}, current value is${bar}.
</message>
?????</field-validator>
? </field>
? <fieldname="bar2">
?????<field-validator type="regex">
?????????<paramname="regex">[0-9],[0-9]</param>
?????????<message>
The value of bar2 must be in the format "x, y", where x and yare between 0 and 9
</message>
????</field-validator>
? </field>
? <fieldname="date">
?????<field-validator type="date">
?????????<paramname="min">12/22/2002</param>
?????????<paramname="max">12/25/2002</param>
?????????<message>The date must be between12-22-2002 and12-25-2002.</message>
?????</field-validator>
? </field>
? <fieldname="foo">
?????<field-validator type="int">
?????????<paramname="min">0</param>
?????????<paramname="max">100</param>
?????????<message key="foo.range">Could notfind foo.range!</message>
?????</field-validator>
? </field>
? <validatortype="expression">
?????<param name="expression">foo lt bar</param>
?????<message>Foo must be greater thanBar. Foo = ${foo}, Bar =${bar}.</message>
?</validator>
</validators>
?
我们看看上面的配置文件,首先每一个validatior都必须有一个type属性,type属性的值为我们前面定义的validator的name。
Message提供了校验出错的信息,message有一个属性key,通过可以可以找到i18n文件定义的内容,但是key并不是必须的。Message体内部的消息为默认消息,当i18n文件中不存在时表示该消息。消息中可以使用${}来引用被校验的对象例如:${foo},${bar}
?
5.6节:Validator和Field Validator
Field Validator用来校验一个字段,例如:
<field name="email_address">
? <field-validatortype="required">
?????<message>You cannot leave the emailaddress field empty.</message>
?</field-validator>
? <field-validatortype="email">
?????<message>The email address youentered is not valid.</message>
?</field-validator>
</field>
Filed validator可以从filed集成字段名字,这样可以将摸个Field的所有的校验局限在一定的范围内。
?
使用Validator可以校验多个字段之间的关系,例如:
<validator type="expression>
????????<param name="expression">foo gtbar</param>
????????<message>foo must be great thanbar.</message>
</validator>
Validator也可以校验一个字段,例如:
<validator type="required">
???????<paramname="fieldName">bar</param>
???????<message>You must enter a value forbar.</message>
</validator>
但是为了将一个字段的所有校验放在一起,我们倾向于尽量使用field validator
?
5.7节:短路(Short-Circuiting)
参看如下例子:
<!DOCTYPE validators PUBLIC
???????"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
???????"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
? <!-- Field Validators foremail field -->
? <fieldname="email">
?????<field-validator type="required"short-circuit="true">
?????????<message>You must enter a value foremail.</message>
?????</field-validator>
?????<field-validator type="email"short-circuit="true">
?????????<message>Not a valide-mail.</message>
?????</field-validator>
? </field>
? <!-- Field Validators foremail2 field -->
? <fieldname="email2">
????<field-validator type="required">
?????????<message>You must enter a value foremail2.</message>
?????</field-validator>
????<field-validator type="email">
?????????<message>Not a valide-mail2.</message>
?????</field-validator>
? </field>
? <!-- Plain Validator 1-->
? <validatortype="expression">
?????<paramname="expression">email.equals(email2)</param>
?????<message>Email not the same asemail2</message>
?</validator>
? <!-- Plain Validator 2-->
? <validator type="expression"short-circuit="true">
?????<paramname="expression">email.startsWith('mark')</param>
?????<message>Email does not start withmark</message>
?</validator>
</validators>
?
校验的顺序:首先Validator,其次Field Validator,但是在Validator或者FieldValidator执行的过程中,顺序按照xml文件中的定义。短路的意思是,一旦一个短路的校验出错,其余后续的校验将不再进行。例如上述的顺序是:
1)Plain Validator 1
2)Plain Validator 2
3)Field Validators for email field
4)Field Validators for email2 field
?
由于Validator 2是短路的,一旦Validator 2校验出错,则email和email2都不会进入校验过程。
?
?
5.8节:validate方法
ActionSupport实现了Validatable接口,这个接口中定义了一个validate方法,通过重写validate方法可以完成更详细的校验,例如:
public void validate() {
? User user = getUser();
? if (StringUtils.isBlank(user.getName())){
???addActionError(getText("user.name.empty"));
? }
? if (StringUtils.isBlank(user.getAddress())){
???addActionError(getText("user.address.empty"));
? }
}
ActionSupport同时也实现了ValidationAware接口,该接口提供了addActionError等输出错误消息的方法。