参数校验在项目中是很常见的。SpringBoot使用 @Valid注解 + BindingResult 来实现参数校验
1.新建User对象
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@Data //自动添加getter setter toString方法
public class User {
@NotEmpty(message="姓名不能为空")
private String name;
@Max(value = 100, message = "年龄不能大于 100 岁")
@Min(value= 18 ,message= "必须年满 18 岁!" )
private int age;
@NotEmpty(message="密码不能为空")
@Length(min=6,message="密码长度不能小于 6 位,不能多于18位",max = 18)
private String pass;
}
2.参数校验
@RequestMapping("/saveUser")
public String saveUser(@Valid User user, BindingResult result) {
System.out.println("user:"+user);
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getCode() + "-" + error.getDefaultMessage());
}
return "error";
}
return "success";
}
3.测试
http://127.0.0.1:8081/saveUser