Struts2校驗器(二)之註解
阿新 • • 發佈:2019-02-01
為了在Action類通過指定驗證規則,只要使用驗證器註解修飾Action裡各成員對應的setter方法即可。
public class RegistAction extends ActionSupport { // 定義4個成員變數封裝請求引數 private String name; private String pass; private int age; private Date birth; // name的setter和getter方法 // 使用註解指定必填、正則表示式兩個校驗規則 @RequiredStringValidator(key = "name.requried" , message = "") @RegexFieldValidator(regex = "\\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 = "") @RegexFieldValidator(regex = "\\w{4,25}" ,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方法 @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; } }
如果要實現手動完成輸入校驗,那麼除了可以在繼承介面的ActionSupport中,實現validate()的方法,當然也可自己定義某個邏輯處理和方法XX(),然後用validateXX()的方法,就可在執行XX()方法時,自動去執行validateXX()方法。