对一些请求参数进行判断,比如检验某些参数的类型,长度,是否为空,甚至是否符合某种规则。
在php中 需要单独对某个请求参数进行判断,那在java中呢?
背景 用户登录请求
假设在用户登录时候,登录请求的时候要求有手机号&验证码。对请求参数的校验基本是手机号参数不能为空,手机号参数11位,1开头 剩余10位数字;验证码参数不能为空,长度是6位。
代码
@RestController
public class LoginController {
@RequestMapping(value = "/login")
public String index(@Validated LoginRequestVo requestVo, BindingResult result) {
// 如果有错误的话,就返回第一个错误
if (result.hasErrors()) {
return result.getAllErrors().get(0).getDefaultMessage();
}
return "login";
}
}
public class LoginRequestVo {
@Pattern(regexp = "^1[0-9]{10}$", message = "don't match")
@NotNull(message = "phone is null")
private String phone;
@NotNull(message = "vcode is null")
@Min(100000)
@Max(999999)
private Integer vcode;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getVcode() {
return vcode;
}
public void setVcode(Integer vcode) {
this.vcode = vcode;
}
}
请求
其他的注解有
AssertFalse
AssertTrue
DecimalMax
DecimalMin
Digits
Future
Max
Min
NotNull
Null
Past
Pattern
Size