Struts2校验框架(validation)

Struts2的校验方法也是挺常用的,找到了一篇挺全面的文章,主要包括以下内容:

  1. 使用Annotation(注解)进行校验
  2. 使用xml配置校验
  3. 使用覆盖validate方法校验 文章出处:http://blog.csdn.net/struts2/archive/2007/08/02/1721989.aspx 作者:马召

5.1节:校验类型和配置方法说明

从Struts2 校验框架在验证的场所上可以分为:客户端校验和服务端校验。
客户端校验是指,在HTML画面上自动生成JavaScript校验代码,在用户提交到服务器之前在客户端浏览器中进行校验。默认位客户端校验。
服务端校验是指,在数据提交到服务器上之后,在Action处理之前,对客户但提交的数据进行校验。 从Struts2校验框架的配置上可以分为:Java Annotation配置和XML配置文件配置
Java Annotation配置是指,使用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配置校验

import com.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;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validation;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@Validation()
public class RegisterAction extends ActionSupport {
    private String name;
    private String password;
    private String rePassword;
    private String mail;
    private String description;

    public String getName() {
        return name;
    }

    @RequiredFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "name is required")
    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    @RequiredFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "password is required")
    @StringLengthFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "password must has proper legnth",
            minLength = "5", maxLength = "12")
    public void setPassword(String password) {
        this.password = password;
    }

    public String getRePassword() {
        return rePassword;
    }

    @RequiredFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true,
            message = "input password again please!")
    @StringLengthFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "password must has proper legnth",
            minLength = "5", maxLength = "12")
    @FieldExpressionValidator(expression = "password eq rePassword",
            message = "two password must match")
    public void setRePassword(String rePassword) {
        this.rePassword = rePassword;
    }

    public String getMail() {
        return mail;
    }

    @RequiredFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "mail is required")
    public void setMail(String mail) {
        this.mail = mail;
    }

    public String getDescription() {
        return description;
    }

    @RequiredFieldValidator(type = ValidatorType.FIELD,
            shortCircuit = true, message = "description is required")
    public void setDescription(String description) {
        this.description = description;
    }

    public String execute() throws Exception {

        return SUCCESS;
    }
}

5.5节:使用XML配置Validation

Xml配置文件与Action的关系为:
SomeAction.java – SomeAction-validation.xml
且与SomeAction.class处在相同的目录中。
SimpleAction-validation.xml文件示例:

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
       "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
  <field name="bar">
      <field-validator type="required">
          <message>You must enter a value for bar.</message>
      </field-validator>
      <field-validator type="int">
          <param name="min">6</param>
          <param name="max">10</param>
          <message>
bar must be between ${min} and ${max}, current value is ${bar}.
</message>
      </field-validator>
  </field>
  <field name="bar2">
      <field-validator type="regex">
          <param name="regex">[0-9],[0-9]</param>
          <message>
The value of bar2 must be in the format "x, y", where x and y are between 0 and 9
</message>
     </field-validator>
  </field>
  <field name="date">
      <field-validator type="date">
          <param name="min">12/22/2002</param>
          <param name="max">12/25/2002</param>
          <message>The date must be between 12-22-2002 and 12-25-2002.</message>
      </field-validator>
  </field>
  <field name="foo">
      <field-validator type="int">
          <param name="min">0</param>
          <param name="max">100</param>
          <message key="foo.range">Could not find foo.range!</message>
      </field-validator>
  </field>
  <validator type="expression">
      <param name="expression">foo lt bar </param>
      <message>Foo must be greater than Bar. 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-validator type="required">
      <message>You cannot leave the email address field empty.</message>
  </field-validator>
  <field-validator type="email">
      <message>The email address you entered is not valid.</message>
  </field-validator>
</field>

Filed validator可以从filed集成字段名字,这样可以将摸个Field的所有的校验局限在一定的范围内。 使用Validator可以校验多个字段之间的关系,例如:

<validator type="expression>
         <param name="expression">foo gt bar</param>
         <message>foo must be great than bar.</message>
</validator>

Validator也可以校验一个字段,例如:

<validator type="required">
        <param name="fieldName">bar</param>
        <message>You must enter a value for bar.</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 for email field -->
  <field name="email">
      <field-validator type="required" short-circuit="true">
          <message>You must enter a value for email.</message>
      </field-validator>
      <field-validator type="email" short-circuit="true">
          <message>Not a valid e-mail.</message>
      </field-validator>
  </field>
  <!-- Field Validators for email2 field -->
  <field name="email2">
     <field-validator type="required">
          <message>You must enter a value for email2.</message>
      </field-validator>
     <field-validator type="email">
          <message>Not a valid e-mail2.</message>
      </field-validator>
  </field>
  <!-- Plain Validator 1 -->
  <validator type="expression">
      <param name="expression">email.equals(email2)</param>
      <message>Email not the same as email2</message>
  </validator>
  <!-- Plain Validator 2 -->
  <validator type="expression" short-circuit="true">
      <param name="expression">email.startsWith('mark')</param>
      <message>Email does not start with mark</message>
  </validator>
</validators>

校验的顺序:首先Validator,其次Field Validator,但是在Validator或者Field Validator执行的过程中,顺序按照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等输出错误消息的方法。

updatedupdated2024-11-302024-11-30