參數(shù)校驗(yàn)在項(xiàng)目中是很常見的路捧。SpringBoot使用 @Valid注解 + BindingResult 來(lái)實(shí)現(xiàn)參數(shù)校驗(yàn)
1.新建User對(duì)象
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 //自動(dòng)添加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="密碼長(zhǎng)度不能小于 6 位,不能多于18位",max = 18)
private String pass;
}
2.參數(shù)校驗(yàn)
@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.測(cè)試
http://127.0.0.1:8081/saveUser