One: Introduction
In writing the back end, the face of a number of parameters, such as phone numbers, passwords, etc. We often need to write validation logic, when more parameters when we will need to verify the need to write a lot of judgment statement, which resulted in a lot of code redundancy. So I developed a validator parameter, just call verification method to instantiate an object parameter validation for all parameters can be passed in object for verification. Word to complete the verification of all parameters.
Project use case:
Complete the registration of business:
1 @RestController 2 @RequestMapping("/cmpas/user") 3 public class UserController { 4 @Autowired 5 private IUserService iUserService; 6 @Autowired 7 private ResultData resultData; 8 @Autowired 9 private ParameterValidator parameterValidator; 10 @RequestMapping(value = "/register",params = {"PhoneNumber","Password","NickName","RealName","Gender"}) 11 public ResultData register(HttpSession httpSession, User user) 12 { 13 is resultData.setResult (parameterValidator.validate (User)); 14 IF (. ResultData.getResult () the equals (ParameterValidator.SUCESS)) 15 { 16 // verify successful . 17 IF (iUserService.insert (User)) 18 is resultData. setResult ( "registered successfully" ); 19 the else 20 resultData.setResult ( "registration failed" ); 21 } 22 // the cause of the error returned 23 return resultData; 24- } 25 }
II: development scenario simulation (registered users)
1: user entity
public class User{ private String Username; private String Password; //get、set方法
}
2: development of its own parameters validator (Inherited abstract class AbstractParameterValidator, writing own validation method)
ParameterValidator the extends AbstractParameterValidator {class public
// check username method public String the Username (String STR) { String = Back "user name is not valid"; // error String regex = "[0-9a-zA -Z] { 1,12} "; // regular expression return str.matches (regex) SUCCESS:? back; // return } // check password method public String password (String str) { String the Back =" password invalid " ; String REGEX = "[0-9a-zA-the Z] {8,20}"; return str.matches (REGEX) SUCCESS:? Back; } }
2: Create a new user entity
= The User new new user the User (); // user to assign a user instance user.setUsername ( "HumorChen"); user.setPassword ( "123456");
Validator exemplary call parameters:
// validator object instantiation parameters
ParameterValidator parameterValidator new new ParameterValidator = ();
// call the check method
String Result = parameterValidator.validate (User);
When invoked only need to use
parameterValidator.validate (user);
all by checking the return value AbstractParameterValidator.SUCCESS
reason otherwise does not pass
Three: Structure
The core method validate (Object ... objects) for all fields of the object passed to the parameters of our own validator class prepared to go in there with the same name method, that is, there is no need to be looking for verification, if required to be check the final results are returned
1 public String validate(Object... objects) { 2 StringBuilder stringBuilder = new StringBuilder(); 3 for (Object object : objects) 4 for (Field field : object.getClass().getDeclaredFields()) { 5 field.setAccessible(true); 6 Method method = null; 7 try { 8 method = this.getClass().getDeclaredMethod(field.getName(), String.class); 9 } catch (Exception e) { } 10 if (method != null) { 11 String result =null; 12 try{ 13 result=(String) method.invoke(this, field.get(object)); 14 //输出日志 15 log(field.getName(),field.get(object),result); 16 }catch (Exception e){} 17 if (!result.equals(SUCESS)) { 18 if (stringBuilder.length() > 0 && (!outputAllError)) 19 return stringBuilder.toString(); 20 stringBuilder.append(result); 21 stringBuilder.append("\n"); 22 } 23 } 24 } 25 return stringBuilder.length() == 0 ? SUCESS : stringBuilder.toString(); 26 }