SpringBoot(五)_表单验证
(1)首先在实体类中增加注解
@Entity
public class Girl {
@Id
@GeneratedValue
private int id;
@NotEmpty(message = "姓名不能为空")
private String name;
@Min(value = 18,message = "未成年禁止入内")
private int age;
public Girl() {
}
(2) 在controller 中增加@Valid + BindingResult
@PostMapping("/girls")
public Girl girlAdd(@Valid Girl girl, BindingResult bindingResult){
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getFieldError().getDefaultMessage());
return null;
}
return girlRepository.save(girl);
}
(3) 测试结果
未成年禁止入内