天天看點

簡單的通用背景校驗代碼

萌生寫這個代碼的原因,是在使用struts2的驗證架構時,總覺的有些不太靈活。當一個action中有多個表單需要處理的時候,struts處理起來就稍微麻煩一點,當校驗失敗時都會return "input"字元串。但我不同表單單校驗失敗後一般都希望傳回不同的result,渲染不同的視圖。另外如果我的校驗是異步發起的,而我想要的結果是json的時候,也比較麻煩。雖然這些問題可以通過修改result type類型和在result中使用ognl表達式來做到,但繞來繞去實在太過麻煩。而若不适用這校驗架構,在action中自己來if else if else 來判斷更不可取。于是便回想到yii和 laravel架構的校驗,這些校驗架構在我看來做的非常優秀,非常靈活,于是我想借鑒它們來自己寫一寫這個校驗插件。

希望的效果

首先,我希望做到兩點

  • 可以對實體進行校驗,不管實體封裝的是表單資料還是資料庫記錄
  • 可以直接對request.getParameterMap()獲得的map進行校驗,這個我暫時還沒完成。
  • 靈活校驗,當校驗失敗後可以馬上通過getErrors拿到錯誤資料,這樣你想咋麼響應怎麼響應,發json也好,把errors傳遞到視圖也好,都可以。
    • 也就是想下面這樣,if(!entity.validate()){....}else{Map map = entity.getErrors()}

另外當實體的屬性沒有被struts填充時,也可以使用我寫的一個fill方法進行填充,為什麼要寫這個呢,因為struts的屬性驅動,類驅動,模型驅動都有點局限,但我的action裡有多個模型,模型驅動隻能為一個模型注值,不夠靈活

1 public class BaseEntity{
 2     public void fill(Map<String, String[]> parameterMap) {
 3         //System.out.println(this.getClass());
 4         Class clazz = this.getClass();
 5         Field fields[] = clazz.getDeclaredFields();
 6         for (int i = 0; i < fields.length; i++) {
 7             String fieldName = fields[i].getName();
 8             //System.out.println(fieldName);
 9             try {
10                 // 查找參數集合
11                 String values [] = parameterMap.get(fieldName);
12                 if(values!=null && values.length>0){
13                     String methodName = "set"+fieldName.substring(0, 1).toUpperCase()
14                         + fieldName.substring(1);
15                     Class fieldType = fields[i].getType();
16                     Method method = clazz.getMethod(methodName,new Class[]{fieldType});
17                     // 設值
18                     method.invoke(this,new Object[]{fieldType.cast(values[0])});
19                 }
20             } catch (Exception e) {
21                 e.printStackTrace();
22             }
23         }
24     }
25     ///...
26 }      

我把代碼放在了

svnchina

github

上,有興趣看看的可以去,有一起做的更好了。

  • http://www.svnchina.com/svn/entity_validator
  • https://github.com/lvyahui8/validator.git

我暫時隻做了對實體的校驗,這裡還有個問題,java本身是強類型的語言。對于實體的某些字段,他的類型本身就存在了校驗,比如一個字段是Integer類型,那你覺得還有必要去校驗他是number類型嗎?完全多次一舉。隻有當屬性是字元串,校驗它是否是number才有意義,比如手機号碼

BaseEntity類

這裡我寫了一個BaseEntity類,如果一個子類要進行校驗,那麼這個子類要覆寫父類的兩個方法,rules和labels方法。這兩個方法,一個用來定義對該試題的校驗規則,一個定義對實體字段的中文翻譯。

1 package org.lyh.validator;
 2 
 3 import java.lang.reflect.Field;
 4 import java.lang.reflect.Method;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 /**
 9  * Created by lvyahui on 2015-06-27.
10  */
11 public class BaseEntity {
12 
13     private Validator validator = new Validator(this);
14 
15     protected Map<String,String> labelMap = new HashMap<String,String>();
16 
17     {
18         String [][] allLabels = labels();
19         if(allLabels != null){
20             for(String [] label : allLabels){
21                 String prop = label[0],propLabel = label[1];
22                 if(prop != null && hasProp(prop) && propLabel != null){
23                     labelMap.put(prop,propLabel);
24                 }
25             }
26         }
27     }
28 
29     public boolean hasProp(String prop) {
30         try {
31             Field field = this.getClass().getDeclaredField(prop);
32             return true;
33         } catch (NoSuchFieldException e) {
34             return false;
35         }
36     }
37 
38     public String getLabel(String prop){
39         return labelMap.get(prop);
40     }
41 
42     public void fill(Map<String, String[]> parameterMap) {
43         //System.out.println(this.getClass());
44         Class clazz = this.getClass();
45         Field fields[] = clazz.getDeclaredFields();
46         for (int i = 0; i < fields.length; i++) {
47             String fieldName = fields[i].getName();
48             //System.out.println(fieldName);
49             try {
50                 // 查找參數集合
51                 String values [] = parameterMap.get(fieldName);
52                 if(values!=null && values.length>0){
53                     String methodName = "set"+fieldName.substring(0, 1).toUpperCase()
54                         + fieldName.substring(1);
55                     Class fieldType = fields[i].getType();
56                     Method method = clazz.getMethod(methodName,new Class[]{fieldType});
57                     // 設值
58                     method.invoke(this,new Object[]{fieldType.cast(values[0])});
59                 }
60             } catch (Exception e) {
61                 e.printStackTrace();
62             }
63         }
64     }
65     
66     /**
67      * 進行校驗
68      * @return 校驗
69      */
70     public boolean validate() {
71         return this.validator.validate();
72     }
73 
74     /**
75      * 如果校驗失敗通過他擷取錯誤資訊
76      * @return 錯誤資訊
77      */
78     public Map<String,Map<String,String>> getErrors(){
79         return this.validator.getErrors();
80     }
81 
82     /**
83      * 校驗規則
84      * @return 校驗規則
85      */
86 
87     public String[][] labels(){return null;}
88 
89     /**
90      * 字段翻譯
91      * @return 字段翻譯
92      */
93     public String [][] rules(){return null;}
94     
95 }      

下面建立一個子類,重寫rules和labels方法。

1 package org.lyh.validator;
 2 
 3 import java.sql.Timestamp;
 4 
 5 /**
 6  * Created by lvyahui on 2015-06-26.
 7  */
 8 
 9 public class UserEntity extends BaseEntity {
10     private String username;
11     private String password;
12     private String name;
13     private Integer gold;
14     private Integer progress;
15     private Timestamp createdAt;
16     private String email;
17     private String phone;
18     private String site;
19     /*省略 getter\setter方法*/
20     @Override
21     public String[][] rules() {
22         return new String [][] {
23                 {"username,password,email,gold,progress,phone","required"},
24                 {"username,password","length","6","14"},
25                 {"rePassword","equals","password"},
26                 {"email","email","\\w{6,12}"},
27                 {"createdAt","timestamp"},
28                 {"phone","number"},
29                 {"site","url"}
30         };
31     }
32 
33     public String[][] labels() {
34         return new String[][]{
35                 {"username","使用者名"},
36                 {"password","密碼"},
37                 {"rePassword","确認密碼"},
38                 {"email","郵箱"},
39                 {"progress","進度"},
40                 {"phone","電話"},
41                 {"gold","金币"}
42         };
43     }
44 
45 }      

可以看到,校驗規則的寫法,很簡單,每一行第一個字元串寫了需要校驗的字段,第二個字元串寫了這些字段應該滿足的規則,後面的字元串是這個規則需要的參數

labels 就更簡單了。

另外這個執行個體化validator類的時候,除了傳遞實體外,還可以傳遞第二個參數,表示是否是短路校驗。

Validator類

下面是這個校驗的核心類Validator

1 package org.lyh.validator;
  2 
  3 import java.lang.reflect.Field;
  4 import java.lang.reflect.Method;
  5 import java.sql.Timestamp;
  6 import java.text.MessageFormat;
  7 import java.util.*;
  8 
  9 /**
 10  * Created by lvyahui on 2015-06-27.
 11  *
 12  */
 13 public class Validator {
 14     /**
 15      * 校驗類型
 16      */
 17     public static final String required = "required";
 18     public static final String length = "length";
 19     public static final String number = "number";
 20     public static final String equals = "equals";
 21     public static final String email = "email";
 22     public static final String url = "url";
 23     public static final String regex = "regex";
 24     public static final String timestamp = "timestamp";
 25 
 26     /**
 27      * 附加參數類型
 28      */
 29     private static final int PATTERN = 1;
 30     private static final int MIN = 2;
 31     private static final int MAX = 3;
 32     private static final int PROP = 4;
 33 
 34     private Map<Integer,Object> params = new HashMap<Integer,Object>();
 35     /**
 36      * 驗證失敗的錯誤資訊,形式如下
 37      * {"username":{"REQUIRED":"使用者名必須為空",...},...}
 38      */
 39     protected Map<String,Map<String,String>> errors
 40         = new HashMap<String,Map<String,String>>();
 41 
 42     /**
 43      * 被校驗的實體
 44      */
 45     private BaseEntity baseEntity;
 46 
 47     /**
 48      * 被校驗實體的類型
 49      */
 50     private Class entityClass = null;
 51 
 52     /**
 53      * 目前正在被校驗的字段
 54      */
 55     private Field field;
 56     /**
 57      * 目前執行的校驗
 58      */
 59     private String validateType ;
 60 
 61     /**
 62      * 目前被校驗字段的值
 63      */
 64     private Object value;
 65 
 66     /**
 67      * 是否短路
 68      */
 69     private boolean direct;
 70 
 71     private String [][] rules ;
 72 
 73     /**
 74      *
 75      * @param baseEntity
 76      */
 77     public Validator(BaseEntity baseEntity) {
 78         this(baseEntity,false);
 79     }
 80 
 81     public Validator(BaseEntity baseEntity,boolean direct){
 82         this.baseEntity = baseEntity;
 83         entityClass = baseEntity.getClass();
 84         rules = baseEntity.rules();
 85     }
 86 
 87     public Map<String,Map<String,String>> getErrors() {
 88         return errors;
 89     }
 90 
 91     public Map<String,String> getError(String prop){
 92         return this.errors.get(prop);
 93     }
 94 
 95     public void addError(String prop,String validatorType,String message){
 96         Map<String,String> error = this.errors.get(prop);
 97         if(error==null || error.size() == 0){
 98             error = new HashMap<String,String>();
 99             errors.put(prop, error);
100         }
101         error.put(validatorType,message);
102     }
103 
104     public void setRules(String[][] rules) {
105         this.rules = rules;
106     }
107 
108     public boolean required(){
109         if(value!=null){
110             if(value.getClass() == String.class && "".equals(((String)value).trim())){
111                 return false;
112             }
113             return true;
114         }
115         return false;
116     }
117 
118     public boolean number(){
119         if(value.getClass().getGenericSuperclass() == Number.class){
120             return true;
121         }else if(((String)value).matches("^\\d+$")){
122             return true;
123         }
124         return false;
125     }
126 
127     public boolean email(){
128         return ((String) value).matches("^\\w+@\\w+.\\w+.*\\w*$");
129     }
130 
131     public boolean url(){
132         return ((String)value).matches("^([a-zA-Z]*://)?([\\w-]+\\.)+[\\w-]+(/[\\w\\-\\.]+)*[/\\?%&=]*$");
133     }
134 
135     public boolean regex(){
136         return ((String)value).matches((String) params.get(regex));
137     }
138 
139     public boolean equals() throws NoSuchFieldException, IllegalAccessException {
140         String prop = (String) params.get(PROP);
141         Field equalsField = entityClass.getDeclaredField(prop);
142         equalsField.setAccessible(true);
143         return value.equals(equalsField.get(baseEntity));
144     }
145     public boolean timestamp(){
146         if(field.getType().equals(Timestamp.class)){
147             return true;
148         }
149         return false;
150     }
151     public boolean length() {
152         String val = (String) value;
153         Integer min = (Integer) params.get(MIN);
154         Integer max = (Integer) params.get(MAX);
155 
156         return val.length() > min && (max == null || val.length() < max);
157 
158 
159     }
160 
161     public boolean validate(){
162         errors.clear();
163         if(rules==null){
164             return true;
165         }
166 
167         for (int i = 0; i < rules.length; i++) {
168             String [] rule = rules[i],fields = rule[0].split(",");
169             validateType = rule[1];
170             setParams(rule);
171             try {
172                 Method validateMethod = this.getClass()
173                     .getMethod(validateType);
174                 for (int j = 0; j < fields.length; j++) {
175                     if(direct && getError(fields[j]) != null){ continue; }
176 
177                     field = entityClass.getDeclaredField(fields[j]);
178                     field.setAccessible(true);
179                     value = field.get(baseEntity);
180                     if(value != null || (value == null && validateType == required)){
181                         if(!(Boolean)validateMethod.invoke(this)){
182                             handleError();
183                         }
184                     }
185                 }
186             } catch (Exception e) {
187                 e.printStackTrace();
188             }
189         }
190         return true;
191     }
192 
193     private void setParams(String [] rule) {
194         params.clear();
195         // 取附加參數
196         switch (validateType){
197             case regex:
198                 params.put(PATTERN,rule[3]);
199                 break;
200             case equals:
201                 params.put(PROP, rule[2]);
202                 break;
203             case length:
204                 if(rule[2] != null) {
205                     params.put(MIN, Integer.valueOf(rule[2]));
206                 }
207                 if(rule.length >= 4){
208                     params.put(MAX,Integer.valueOf(rule[3]));
209                 }
210                 break;
211             default:
212         }
213     }
214 
215     private void handleError() {
216         String name = this.baseEntity.getLabel(field.getName()) != null
217                 ? this.baseEntity.getLabel(field.getName()) : field.getName(),
218                 message = MessageFormat.format(Messages.getMsg(validateType),name);
219         this.addError(field.getName(), validateType, message);
220     }
221 
222 }      

消息模闆

下面是錯誤消息模闆

1 package org.lyh.validator;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 /**
 7  * Created by lvyahui on 2015-06-28.
 8  */
 9 public class Messages {
10     private static Map<String,String> msgMap = new HashMap<String,String>();
11 
12     static{
13         msgMap.put(Validator.required,"{0}必須填寫");
14         msgMap.put(Validator.email,"{0}不合法");
15         msgMap.put(Validator.equals,"{0}與{1}不相同");
16         msgMap.put(Validator.length,"{0}長度必須在{1}-{2}之間");
17         msgMap.put(Validator.regex,"{0}不符合表達式");
18         msgMap.put(Validator.timestamp,"{0}不是合法的日期格式");
19         msgMap.put(Validator.number,"{0}不是數字格式");
20         msgMap.put(Validator.url,"{0}不是合法的url");
21     }
22 
23     public static String getMsg(String validateType) {
24         return msgMap.get(validateType);
25     }
26 }      

測試結果

下面寫個main方法測試

1 package org.lyh.validator;
 2 
 3 /**
 4  * Created by lvyahui on 2015-06-28.
 5  */
 6 public class MainTest {
 7     public static void main(String[] args) {
 8 
 9         UserEntity userEntity = new UserEntity();
10         userEntity.validate();
11         System.out.println(userEntity.getErrors());
12 
13         userEntity.setUsername("lvyahui");
14         userEntity.setRePassword("admin888");
15         userEntity.setPassword("admin888");
16         userEntity.setEmail("lvyaui82.com");
17         userEntity.validate();
18         System.out.println(userEntity.getErrors());
19 
20         userEntity.setEmail("[email protected]");
21         userEntity.setPhone("hjhjkhj7867868");
22         userEntity.setGold(1);
23         userEntity.setSite("www.baidu.com");
24 
25         userEntity.validate();
26 
27         System.out.println(userEntity.getErrors());
28         // ([a-zA-Z]*://)?([\w-]+\.)+[\w-]+(/[\w-]+)*[/?%&=]*
29         userEntity.setSite("http://www.baidu.com/index.php");
30         userEntity.setProgress(123);
31         userEntity.setPhone("156464564512");
32         userEntity.validate();
33 
34         System.out.println(userEntity.getErrors());
35 
36     }
37 
38 }      

運作程式,得到這樣的輸出

1 {gold={required=金币必須填寫}, password={required=密碼必須填寫}, phone={required=電話必須填寫}, progress={required=進度必須填寫}, email={required=郵箱必須填寫}, username={required=使用者名必須填寫}}
2 {gold={required=金币必須填寫}, phone={required=電話必須填寫}, progress={required=進度必須填寫}, email={email=郵箱不合法}}
3 {phone={number=電話不是數字格式}, progress={required=進度必須填寫}}
4 {}      

後面要做的就是直接對map進行校驗

我的想法是通過validator類添加set方法注入規則和翻譯。當然上面的錯誤資訊模闆可以到xml檔案中進行配置,至于校驗規則和翻譯個人認為沒有必要放到xml中去。