這種基于Annotation的輸入校驗實質上也屬于Struts 2“零配置”特性的部分,它允許使用Annotation來定義每個字段應該滿足的規則,Struts 2在com.opensymphony.xwork2.validator.annotations包下提供了大量校驗器相關的Annotation,這些Annotation和前面介紹的驗證器大緻上一一對應,讀者可以自行查閱API文檔。
為了在Action類通過Annotation指定驗證規則,經過如下配置即可:
Ø 使用驗證器Annotation修飾Action裡各屬性對應的setter方法。
下面我們在前面I18NValidate應用的基礎上進行修改,将該應用的WEB-INF\src\lee路徑下的校驗規則檔案删除,修改該路徑下的RegistAction.java檔案,通過注釋指定各屬性應該滿足的規則。修改後的Action代碼如下所示。
程式清單:codes\04\4.2\annotation\WEB-INF\src\org\crazyit\app\action\RegistAction.java
public class RegistAction extends ActionSupport
{
private String name;
private String pass;
private int age;
private Date birth;
//name屬性的setter和getter方法
//使用Annotation指定必填、正規表達式兩個校驗規則
@RequiredStringValidator(key = "name.requried"
, message = "")
@RegexFieldValidator(expression = "\\w{4,25}"
,key = "name.regex" , message = "")
public void setName(String name)
{
this.name = name;
}
public String getName()
return this.name;
//pass屬性的setter和getter方法
@RequiredStringValidator(key = "pass.requried"
,message = "")
,key = "pass.regex" ,message = "")
public void setPass(String pass)
this.pass = pass;
public String getPass()
return this.pass;
//age屬性的setter和getter方法
@IntRangeFieldValidator(message = ""
, key = "age.range", min = "1"
, max = "150")
public void setAge(int age)
this.age = age;
public int getAge()
return this.age;
//birth屬性的setter和getter方法
//使用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代碼中,會給後期維護帶來一定困難。