5.6 基于Annotation的输入校验

这种基于 Annotation 的输入校验实际上是 Struts 2“零配置”特性的部分,它允许使用Annotation 来定义每个字段应该满足的规则。Struts 2 在 com.opensymphony.xwork2.validator. annotations包下提供了大量校验器Annotation,这些Annotation和前面介绍的校验器大致上一一对应,读者可以自行查阅API文档。

为了在Action类中通过Annotation指定校验规则,需要经过如下两项配置。

使用@Validation()Annotation修饰Action类。

使用校验器Annotation修饰Action里各属性对应的setter方法。

下面在前面I18NValidate应用的基础上进行修改,将该应用的WEB-INF/src/lee路径下的校验规则文件删除,修改该路径下的RegistAction.java文件,通过注释指定各属性应该满足的规则。修改后的Action代码如下。

程序清单:codes\05\5.6\Annotation\WEB-INF\src\org\crazyit\struts2\action\RegistAction.java

public class RegistAction extends ActionSupport
{
    private String name;
    private String pass;
    private int age;
    private Date birth;
    // 使用Annotation指定必填、正则表达式两个校验规则
    @RequiredStringValidator(type = ValidatorType.FIELD,
        key = "name.requried",message = "")
    @RegexFieldValidator(type = ValidatorType.FIELD,
        expression = "\\w{4,25}",key = "name.regex",message = "")
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return (this.name);
    }
    // 使用Annotation指定必填、正则表达式两个校验规则
    @RequiredStringValidator(type = ValidatorType.FIELD,
        key = "pass.requried",message = "")
    @RegexFieldValidator(type = ValidatorType.FIELD,
        expression = "\\w{4,25}",key = "pass.regex",message = "")
    public void setPass(String pass)
    {
        this.pass = pass;
    }
    public String getPass()
    {
        return (this.pass);
    }
    // 使用Annotation指定整数范围校验规则
    @IntRangeFieldValidator(message = "",
        key = "age.range", min = "1", max = "150")
    public void setAge(int age)
    {
        this.age = age;
    }
    public int getAge() {
        return (this.age);
    }
    // 使用Annotation指定日期范围校验规则
    @DateRangeFieldValidator(message = "",
        key = "birth.range", min = "1900/01/01", max = "2050/01/21")
    public void setBirth(Date birth)
    {
        this.birth = birth;
    }
    public Date getBirth()
    {
        return (this.birth);
    }
}

上面Action的粗体字代码使用校验器Annotation修饰了各属性的setter方法,这样Struts 2就知道了各属性应该满足怎样的规则。通过在Action中使用Annotation指定各字段应该满足的校验规则,就可以避免书写XML校验规则文件。

提示:

关于使用Annotation来代替XML配置文件,这是JDK 1.5新增Annotation后的一个趋势,使用这种方式无须编写XML文件,从而可以简化应用开发;但带来的副作用是所有内容都被写入Java代码中,会给后期维护带来一定困难。