Java使用Validation進行引數校驗
阿新 • • 發佈:2020-12-14
一.不用springboot,使用validation引數校驗需要自己寫ValidationUtil工具類,來校驗
public class ValidatorUtil {
private static Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
public static <T> Map<String,StringBuffer> validate(T obj){
Map<String,StringBuffer> errorMap = null;
Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
if(set != null && set.size() >0 ){
errorMap = new HashMap<String,StringBuffer>();
String property = null;
for(ConstraintViolation<T> cv : set){
//這裡迴圈獲取錯誤資訊,可以自定義格式
property = cv.getPropertyPath().toString();
if(errorMap.get(property) != null){
errorMap.get(property).append("," + cv.getMessage( ));
}else{
StringBuffer sb = new StringBuffer();
sb.append(cv.getMessage());
errorMap.put(property, sb);
}
}
}
return errorMap;
}
在測試類中的使用方法(片段)
public static void main(String[] args) {
StudentInfo s = new StudentInfo();
long startTime = System.currentTimeMillis();
print(ValidatorUtil.validate(s));
System.out.println("===============耗時(毫秒)=" + (System.currentTimeMillis() - startTime));
二.使用springboot需要加上註解@Validated和引入相關依賴
<!--validate 依賴-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.3</version>
</dependency>
1.使用@valid + BindingResult來處理,並且要在controller裡面寫關於bindingresult返回結果的判斷來列印資訊 (太麻煩)
@PostMapping("/UserRegister")
@ApiOperation("使用者註冊")
public Object userRegister(@Valid UserRegisterForm registerForm, BindingResult bindingResult) {
return userService.UserRegister(registerForm, bindingResult);
}
2.使用全域性異常處理,在controller里加上@valid註解即可,不需要bindingresult,也不用判斷bindingresult返回的值(推薦)
@ControllerAdvice
public class ValidationUtil{
@ExceptionHandler(org.springframework.validation.BindException.class)
@ResponseBody
public ResultVO handleEx(BindException e){
List<FieldError> fieldErrors = e.getFieldErrors();
StringBuilder sb = new StringBuilder();
for(FieldError fe: fieldErrors){
sb.append("屬性:").append(fe.getField()).append("校驗不通過:").append(fe.getDefaultMessage()).append("; ");
}
log.info("引數錯誤 : "+sb);
return ResultVOUtil.error(sb);
}
}
測試程式碼:
@Data
public class LoginForm {
@NotNull(message = "手機號不能為空")
@ApiModelProperty("手機號")
private String phone;
@NotNull(message = "密碼不能為空")
@ApiModelProperty("密碼")
private String password;
@NotNull(message = "驗證碼不能為空")
@ApiModelProperty("驗證碼")
private String securityCode;
// @NotNull(message = "驗證碼不能為空")
// @ApiModelProperty("驗證碼")
// private String securityCode;
}
執行案例: