Data validation he parameter controls the use of the common mechanism -WebDataBinder
WebDataBinder mechanism [authentication parameters acquisition parameters --- --- --- Conversion Parameters Controller
springMVC support for JSR-303 annotations verification, support for custom validation.
[1] is introduced using jar: validation-api-1.0.0.GA.jar: JDK interface; hibernate-validator-4.2.0.Final.jar achieve the above interface;
2. [Handling] @NotNull ( message = "id can not be blank") @Min (value = 1, message = " minimum to 1")
add annotations @Valid + parameters to be verified on the results obtained [3] the method and @Valid --- objects need to pass BindingResult
public Object getCardInfoDetailtemp(@Valid CardInfoDTO info,BindingResult bindingResult)
{
OutputObjectCSF obj = new OutputObjectCSF();
if (bindingResult.hasErrors()) {
obj.setRtnCode(ReturnInfoEnums.PROCESS_PARAMETER_ERROR.getCode());
obj.setRtnMsg(bindingResult.getAllErrors().get(0).getDefaultMessage());
return obj;
}
return obj;
}
Example 4
POJO
//数据验证测试
@Data
@Component
public class User {
@NotNull(message = "id不能为空")
private Long id;
//@Future(message = "时间只能是未来")
@Past(message = "时间只能是过去")
@DateTimeFormat(pattern = "yyyy-MM-dd") //格式转换
private Date date;
@DecimalMax(value = "100000.00",message = "不能超过100000") //最大值
@DecimalMin(value = "0.1",message = "不能小于0.1") //最小值
private Double money;
//@Range(min = 1,max = 100) //1-100之间的范围内
@Max(100) //最大值
@Min(1) //最小值
private Integer age;
//message: 格式不正确时返回信息
@Email(message = "邮箱格式错误")
private String email;
@Size(min = 5,max = 50) //字符串长度范围
private String size;
}
data verification
/**
* 数据验证
* @Valid: 表示需要开启验证这个实体
* @param user
* @param errors 错误信息,由springMVC验证之后自动填充
* @return
*/
@GetMapping("/vaild")
public Map<String,Object> vaildUser(@Valid @RequestBody User user, Errors errors){
Map<String,Object> result=new HashMap<>();
//获取验证结果
errors.getAllErrors().stream().forEach(x->{
String key=null;
if(x instanceof FieldError){ //字段错误
FieldError fe= (FieldError) x;
key=fe.getField();
}else{ //非字段错误
key=x.getObjectName();
String defaultMessage = x.getDefaultMessage();
}
result.put(key,x.getDefaultMessage());
});
return result;
}