好处:方便了后端对HTTP请求中参数进行核验,只需一次编写效验器,一行代码便可对所有参数的pojo进行参数核验!而且更改效验逻辑时只需要更改效验器类即可,实现了解耦合。
只需要程序员按照规范开发一个ParameterValidator类(如下图1),将所有效验方法写在该类中即可在任意地方使用一行代码实现对所有参数的核验(如下图2)
图1:(图中写了对手机号码和密码进行核验的方法)
图二:
Jar包:ParameterValidator.jar
url:http://xingxunxinxi.com/ParameterValidator.jar
项目结构:
com.xingxunxinxi.ParameterValidator包含该套参数验证器服务的接口和默认实现类
HTTP请求参数验证器服务接口:ParameterValidateService
1 package com.xingxunxinxi.ParameterValidator; 2 3 /** 4 * 5 * 项目名称:ParameterValidator 6 * 类名称: ParameterValidator 7 * 类描述: ParameterValidateService interface 8 * 创建人: HumorChen 9 * 创建时间:2019年4月20日 下午7:48:51 10 * 修改时间:2019年4月20日 下午7:48:51 11 * 修改备注: 12 * 13 */14 public interface ParameterValidateService {15 String SUCCESS="SUCCESS";16 public String validate(Object...objects)throws Exception;17 }
默认实现类:DefaultParameterValidateService
1 package com.xingxunxinxi.ParameterValidator; 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Method; 5 /** 6 * 7 * 8 * 项目名称:ParameterValidator 9 * 类名称: DefaultParameterValidateService 10 * 类描述: DefaultParameterValidateService 11 * 创建人: HumorChen 12 * 创建时间:2019年4月20日 下午11:46:47 13 * 修改时间:2019年4月20日 下午11:46:47 14 * 修改备注: 15 * 16 */ 17 public class DefaultParameterValidateService implements ParameterValidateService { 18 //false means return first failure reason,true means return all reasons. 19 private boolean AllResult=false; 20 //whether inner-validator is initialized 21 private boolean initialized=false; 22 //inner validator object 23 private Object validator; 24 //exception message 25 private static String notValidatorExceptionMessage="This object is not an instance of ParameterValidator"; 26 //separate reason 27 public static String ReasonSeparator="\n"; 28 public DefaultParameterValidateService() 29 { 30 31 } 32 /** 33 * parameter AllResult is true means return all fail reasons when validating,false means return the first failure reason 34 * @param boolean 35 */ 36 public DefaultParameterValidateService(boolean AllResult) 37 { 38 this.AllResult=AllResult; 39 } 40 /** 41 * initialize the validator of ParameterValidatorService 42 * @param class 43 * @throws Exception 44 */ 45 public void init(Class validatorclass) throws Exception 46 { 47 init(validatorclass.newInstance()); 48 } 49 /** 50 * initialize the validator of ParameterValidatorService 51 * @param Object 52 * @throws Exception 53 */ 54 public void init(Object object) throws Exception 55 { 56 if(isValidator(object)) 57 { 58 this.validator=object; 59 initialized=true; 60 System.out.println(this.getClass().getSimpleName()+" initialize success"); 61 } 62 } 63 /** 64 * initialize the validator of ParameterValidatorService 65 * @param String 66 * @throws Exception 67 */ 68 public void init(String classname) throws Exception 69 { 70 init(Class.forName(classname).newInstance()); 71 } 72 /** 73 * judge whether the object is a validator. 74 * reference ParametorValidatorDemo 75 * method-ruler: 76 * method-name:your property name 77 * returnType: String 78 * parameterCount:1 79 * parameterType:Object 80 * @param object 81 * @return boolean 82 * @throws Exception 83 */ 84 private boolean isValidator(Object object) throws Exception 85 { 86 for(Method method:object.getClass().getDeclaredMethods()) 87 if(method.getParameterCount()==1&&method.getReturnType().equals(String.class)&&method.getParameterTypes()[0].equals(Object.class)) 88 return true; 89 else 90 throw new Exception(notValidatorExceptionMessage); 91 return false; 92 } 93 94 public static void setReasonSeparator(String reasonSeparator) { 95 ReasonSeparator = reasonSeparator; 96 } 97 98 public boolean isAllResult() { 99 return AllResult;100 }101 public void setAllResult(boolean allResult) {102 AllResult = allResult;103 }104 /**105 * validate objects' properties106 * @param objects107 * @return String:validate_result108 */109 public String validate(Object... objects) throws Exception {110 if(initialized)111 {112 String result="";113 for(Object object:objects)114 for(Field field:object.getClass().getDeclaredFields())115 {116 field.setAccessible(true);117 String fieldresult=(String) validator.getClass().getMethod(field.getName(), Object.class).invoke(validator, field.get(object));118 if(AllResult)119 {120 if(!fieldresult.equals(SUCCESS))121 result+=fieldresult+ReasonSeparator;122 }123 else124 {125 if(!fieldresult.equals(SUCCESS))126 return fieldresult;127 }128 }129 return result==""?SUCCESS:result.substring(0, result.length()-ReasonSeparator.length());130 }131 else132 throw new Exception("ParameterValidator not initialized Exception");133 }134 135 }
示范包:
com.xingxunxinxi.ParameterValidator.Demo
示范参数验证器类:
1 package com.xingxunxinxi.ParameterValidator.Demo; 2 3 import com.xingxunxinxi.ParameterValidator.ParameterValidateService; 4 5 /** 6 * 7 * 8 * 项目名称:ParameterValidator 9 * 类名称: ParameterValidatorDemo 10 * 类描述: ParameterValidatorDemo11 * 创建人: HumorChen 12 * 创建时间:2019年4月20日 下午10:07:27 13 * 修改时间:2019年4月20日 下午10:07:27 14 * 修改备注: 15 *16 */17 public class ParameterValidatorDemo {18 /**19 * we use this method below to validate object's property which named phoneNumber,if phoneNumber's value is legal,this method will return20 * ParameterValidateService.SUCCESS,or return your individual tip.21 * @param object22 * @return String23 */24 public String phoneNumber(Object object)25 {26 String result="illegal phone number";27 String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";28 if(((String)object).matches(regex))29 return ParameterValidateService.SUCCESS;30 return result;31 }32 /**33 * we use this method below to validate object's property which named password,if password's value is legal,this method will return34 * ParameterValidateService.SUCCESS,or return your individual tip.35 * @param object36 * @return37 */38 public String password(Object object)39 {40 String result="illegal password";41 String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";42 if(((String)object).matches(regex))43 return ParameterValidateService.SUCCESS;44 return result;45 }46 }
示范调用类:
1 package com.xingxunxinxi.ParameterValidator.Demo; 2 3 import com.xingxunxinxi.ParameterValidator.DefaultParameterValidateService; 4 /** 5 * 6 * 7 * 项目名称:ParameterValidator 8 * 类名称: UseDemo 9 * 类描述: DefaultParameterValidateService use demo10 * 创建人: HumorChen 11 * 创建时间:2019年4月20日 下午11:47:20 12 * 修改时间:2019年4月20日 下午11:47:20 13 * 修改备注: 14 *15 */16 public class UseDemo {17 static DefaultParameterValidateService dpvs = new DefaultParameterValidateService();18 static {19 try {20 dpvs.init(ParameterValidatorDemo.class);21 } catch (Exception e) {22 System.out.println("initialization failure");23 e.printStackTrace();24 }25 }26 27 public static void main(String[] args) {28 String legalphone = "15073207380";29 String illegalphone = "1507320738";30 31 String legalpassword="12345678ABC";32 String illegalpassword="12345";33 34 User user = new User();35 user.setPhoneNumber(legalphone);36 user.setPassword(legalpassword);37 try {38 System.out.println(user.toString() + "validate result: "39 + dpvs.validate(user));40 user.setPhoneNumber(illegalphone);41 System.out.println(user.toString() + "validate result: "42 + dpvs.validate(user));43 user.setPassword(illegalpassword);44 System.out.println(user.toString() + "validate result: "45 + dpvs.validate(user));46 dpvs.setAllResult(true);47 System.out.println(user.toString() + "validate result: "48 + dpvs.validate(user));49 } catch (Exception e) {50 e.printStackTrace();51 }52 // System.out.println(new ParameterValidatorDemo().phoneNumber("15073207380"));53 }54 /**55 * 56 * 57 * 项目名称:ParameterValidator 类名称: User 类描述: your entity 创建人: HumorChen58 * 创建时间:2019年4月20日 下午10:31:51 修改时间:2019年4月20日 下午10:31:51 修改备注:59 * 60 */61 62 }63 64 class User {65 private String phoneNumber;66 private String password;67 68 public String getPhoneNumber() {69 return phoneNumber;70 }71 72 public void setPhoneNumber(String phoneNumber) {73 this.phoneNumber = phoneNumber;74 }75 76 public String getPassword() {77 return password;78 }79 80 public void setPassword(String password) {81 this.password = password;82 }83 public String toString()84 {85 return "phoneNumber:"+phoneNumber+"\npassword:"+password+"\n";86 }87 }
示范调用类运行结果:
DefaultParameterValidateService initialize success
phoneNumber:15073207380password:12345678ABCvalidate result: SUCCESSphoneNumber:1507320738password:12345678ABCvalidate result: illegal phone numberphoneNumber:1507320738password:12345validate result: illegal phone numberphoneNumber:1507320738password:12345validate result: illegal phone numberillegal password附:
该套HTTP请求参数验证器服务ParamertValidateService,只需要写一个参数验证器的类,该类中为每个需要验证的参数写个同名方法(参数为Object object),在方法内写自己的验证逻辑,验证通过则返回ParameterValidateService.SUCCESS,否则返回自定义错误提示,可选择单错误提示模式和全错误提示模式,单错误提示模式下当验证器发现参数不合法时会立马将该错误返回,而全错误模式下会验证完所有参数后,将所有错误原因返回(以DefaultParameterValidateService.ReasonSeparator分隔,可自定义)。调用该服务时只需要这样写DefaultParameterValidateService.validate(POJO pojo);即可对pojo内所有属性进行验证,并将结果返回。所有参数验证全部通过则返回ParameterValidateService.SUCCESS,否则返回错误提示。