Struts2-Validation

编程技术  /  houtizong 发布于 3年前   73
Struts2-Validation         非原创

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  实现modelDriven,应在action的setActionForm前面定义
    可以将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()
publicclass RegisterAction extends ActionSupport {
    private String name;
    private String password;
    private String rePassword;
    private String mail;
    private String description;

    public String getName() {
        returnname;
    }

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

    public String getPassword() {
        returnpassword;
    }

    @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")
    publicvoid setPassword(String password) {
        this.password = password;
    }

    public String getRePassword() {
        returnrePassword;
    }

    @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")
    publicvoid setRePassword(String rePassword) {
        this.rePassword = rePassword;
    }

    public String getMail() {
        returnmail;
    }

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

    public String getDescription() {
        returndescription;
    }

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

    public String execute() throws Exception {

        returnSUCCESS;
    }
}

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 >
      <field-validator type="required">
          <message>You must enter a value for bar.</message>
      </field-validator>
      <field-validator type="int">
          <param >6</param>
          <param >10</param>
          <message>
bar must be between ${min} and ${max}, current value is ${bar}.
</message>
      </field-validator>
</field>
<field >
      <field-validator type="regex">
          <param >[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 >
      <field-validator type="date">
          <param >12/22/2002</param>
          <param >12/25/2002</param>
          <message>The date must be between 12-22-2002 and 12-25-2002.</message>
      </field-validator>
</field>
<field >
      <field-validator type="int">
          <param >0</param>
          <param >100</param>
          <message key="foo.range">Could not find foo.range!</message>
      </field-validator>
</field>
<validator type="expression">
      <param >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 >
<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 >foo gt bar</param>
         <message>foo must be great than bar.</message>
</validator>
Validator也可以校验一个字段,例如:
<validator type="required">
        <param >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 >
      <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 >
     <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 >email.equals(email2)</param>
      <message>Email not the same as email2</message>
</validator>
<!-- Plain Validator 2 -->
<validator type="expression" short-circuit="true">
      <param >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等输出错误消息的方法

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客