好处:方便了后端对HTTP请求中参数进行核验,只需一次编写效验器,一行代码便可对所有参数的pojo进行参数核验!而且更改效验逻辑时只需要更改效验器类即可,实现了解耦合。
只需要程序员按照规范开发一个ParameterValidator类(如下图1),将所有效验方法写在该类中即可在任意地方使用一行代码实现对所有参数的核验(如下图2)
图1:(图中写了对手机号码和密码进行核验的方法)
图二:
Jar包:ParameterValidator.jar
url:http://xingxunxinxi.com/ParameterValidator.jar
项目结构:
com.xingxunxinxi.ParameterValidator包含该套参数验证器服务的接口和默认实现类
HTTP请求参数验证器服务接口:ParameterValidateService
package com.xingxunxinxi.ParameterValidator; /**
*
* 项目名称:ParameterValidator
* 类名称: ParameterValidator
* 类描述: ParameterValidateService interface
* 创建人: HumorChen
* 创建时间:2019年4月20日 下午7:48:51
* 修改时间:2019年4月20日 下午7:48:51
* 修改备注:
*
*/
public interface ParameterValidateService {
String SUCCESS="SUCCESS";
public String validate(Object...objects)throws Exception;
}
默认实现类:DefaultParameterValidateService
package com.xingxunxinxi.ParameterValidator; import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
*
*
* 项目名称:ParameterValidator
* 类名称: DefaultParameterValidateService
* 类描述: DefaultParameterValidateService
* 创建人: HumorChen
* 创建时间:2019年4月20日 下午11:46:47
* 修改时间:2019年4月20日 下午11:46:47
* 修改备注:
*
*/
public class DefaultParameterValidateService implements ParameterValidateService {
//false means return first failure reason,true means return all reasons.
private boolean AllResult=false;
//whether inner-validator is initialized
private boolean initialized=false;
//inner validator object
private Object validator;
//exception message
private static String notValidatorExceptionMessage="This object is not an instance of ParameterValidator";
//separate reason
public static String ReasonSeparator="\n";
public DefaultParameterValidateService()
{ }
/**
* parameter AllResult is true means return all fail reasons when validating,false means return the first failure reason
* @param boolean
*/
public DefaultParameterValidateService(boolean AllResult)
{
this.AllResult=AllResult;
}
/**
* initialize the validator of ParameterValidatorService
* @param class<?>
* @throws Exception
*/
public void init(Class<?>validatorclass) throws Exception
{
init(validatorclass.newInstance());
}
/**
* initialize the validator of ParameterValidatorService
* @param Object
* @throws Exception
*/
public void init(Object object) throws Exception
{
if(isValidator(object))
{
this.validator=object;
initialized=true;
System.out.println(this.getClass().getSimpleName()+" initialize success");
}
}
/**
* initialize the validator of ParameterValidatorService
* @param String
* @throws Exception
*/
public void init(String classname) throws Exception
{
init(Class.forName(classname).newInstance());
}
/**
* judge whether the object is a validator.
* reference ParametorValidatorDemo
* method-ruler:
* method-name:your property name
* returnType: String
* parameterCount:1
* parameterType:Object
* @param object
* @return boolean
* @throws Exception
*/
private boolean isValidator(Object object) throws Exception
{
for(Method method:object.getClass().getDeclaredMethods())
if(method.getParameterCount()==1&&method.getReturnType().equals(String.class)&&method.getParameterTypes()[0].equals(Object.class))
return true;
else
throw new Exception(notValidatorExceptionMessage);
return false;
} public static void setReasonSeparator(String reasonSeparator) {
ReasonSeparator = reasonSeparator;
} public boolean isAllResult() {
return AllResult;
}
public void setAllResult(boolean allResult) {
AllResult = allResult;
}
/**
* validate objects' properties
* @param objects
* @return String:validate_result
*/
public String validate(Object... objects) throws Exception {
if(initialized)
{
String result="";
for(Object object:objects)
for(Field field:object.getClass().getDeclaredFields())
{
field.setAccessible(true);
String fieldresult=(String) validator.getClass().getMethod(field.getName(), Object.class).invoke(validator, field.get(object));
if(AllResult)
{
if(!fieldresult.equals(SUCCESS))
result+=fieldresult+ReasonSeparator;
}
else
{
if(!fieldresult.equals(SUCCESS))
return fieldresult;
}
}
return result==""?SUCCESS:result.substring(0, result.length()-ReasonSeparator.length());
}
else
throw new Exception("ParameterValidator not initialized Exception");
} }
示范包:
com.xingxunxinxi.ParameterValidator.Demo
示范参数验证器类:
package com.xingxunxinxi.ParameterValidator.Demo; import com.xingxunxinxi.ParameterValidator.ParameterValidateService; /**
*
*
* 项目名称:ParameterValidator
* 类名称: ParameterValidatorDemo
* 类描述: ParameterValidatorDemo
* 创建人: HumorChen
* 创建时间:2019年4月20日 下午10:07:27
* 修改时间:2019年4月20日 下午10:07:27
* 修改备注:
*
*/
public class ParameterValidatorDemo {
/**
* we use this method below to validate object's property which named phoneNumber,if phoneNumber's value is legal,this method will return
* ParameterValidateService.SUCCESS,or return your individual tip.
* @param object
* @return String
*/
public String phoneNumber(Object object)
{
String result="illegal phone number";
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}$";
if(((String)object).matches(regex))
return ParameterValidateService.SUCCESS;
return result;
}
/**
* we use this method below to validate object's property which named password,if password's value is legal,this method will return
* ParameterValidateService.SUCCESS,or return your individual tip.
* @param object
* @return
*/
public String password(Object object)
{
String result="illegal password";
String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$";
if(((String)object).matches(regex))
return ParameterValidateService.SUCCESS;
return result;
}
}
示范调用类:
package com.xingxunxinxi.ParameterValidator.Demo; import com.xingxunxinxi.ParameterValidator.DefaultParameterValidateService;
/**
*
*
* 项目名称:ParameterValidator
* 类名称: UseDemo
* 类描述: DefaultParameterValidateService use demo
* 创建人: HumorChen
* 创建时间:2019年4月20日 下午11:47:20
* 修改时间:2019年4月20日 下午11:47:20
* 修改备注:
*
*/
public class UseDemo {
static DefaultParameterValidateService dpvs = new DefaultParameterValidateService();
static {
try {
dpvs.init(ParameterValidatorDemo.class);
} catch (Exception e) {
System.out.println("initialization failure");
e.printStackTrace();
}
} public static void main(String[] args) {
String legalphone = "15073207380";
String illegalphone = "1507320738"; String legalpassword="12345678ABC";
String illegalpassword="12345"; User user = new User();
user.setPhoneNumber(legalphone);
user.setPassword(legalpassword);
try {
System.out.println(user.toString() + "validate result: "
+ dpvs.validate(user));
user.setPhoneNumber(illegalphone);
System.out.println(user.toString() + "validate result: "
+ dpvs.validate(user));
user.setPassword(illegalpassword);
System.out.println(user.toString() + "validate result: "
+ dpvs.validate(user));
dpvs.setAllResult(true);
System.out.println(user.toString() + "validate result: "
+ dpvs.validate(user));
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(new ParameterValidatorDemo().phoneNumber("15073207380"));
}
/**
*
*
* 项目名称:ParameterValidator 类名称: User 类描述: your entity 创建人: HumorChen
* 创建时间:2019年4月20日 下午10:31:51 修改时间:2019年4月20日 下午10:31:51 修改备注:
*
*/ } class User {
private String phoneNumber;
private String password; public String getPhoneNumber() {
return phoneNumber;
} public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
public String toString()
{
return "phoneNumber:"+phoneNumber+"\npassword:"+password+"\n";
}
}
示范调用类运行结果:
DefaultParameterValidateService initialize success
phoneNumber:15073207380
password:12345678ABC
validate result: SUCCESS
phoneNumber:1507320738
password:12345678ABC
validate result: illegal phone number
phoneNumber:1507320738
password:12345
validate result: illegal phone number
phoneNumber:1507320738
password:12345
validate result: illegal phone number
illegal password
附:
该套HTTP请求参数验证器服务ParamertValidateService,只需要写一个参数验证器的类,该类中为每个需要验证的参数写个同名方法(参数为Object object),在方法内写自己的验证逻辑,验证通过则返回ParameterValidateService.SUCCESS,否则返回自定义错误提示,可选择单错误提示模式和全错误提示模式,单错误提示模式下当验证器发现参数不合法时会立马将该错误返回,而全错误模式下会验证完所有参数后,将所有错误原因返回(以DefaultParameterValidateService.ReasonSeparator分隔,可自定义)。调用该服务时只需要这样写DefaultParameterValidateService.validate(POJO pojo);即可对pojo内所有属性进行验证,并将结果返回。所有参数验证全部通过则返回ParameterValidateService.SUCCESS,否则返回错误提示。