對一些請求參數進行判斷,比如檢驗某些參數的類型,長度,是否爲空,甚至是否符合某種規則。
在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