用於驗證註解是否符合要求,直接加在變量user之前,在變量中添加驗證信息的要求,當不符合要求時就會在方法中返回message 的錯誤提示信息。
@RestController
@RequestMapping(value = "/user")
public class UserController {
@PostMapping(value = "/get")
public User create (@RequestBody @Valid User user) {
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
user.setId("1");
return user;
}
然後在 User 類中添加驗證信息的要求:
@Data
public class User {
private String id;
@NotBlank(message = "用戶名不能爲空")
private String username;
@NotBlank(message = "密碼不能爲空")
private String password;
}
@NotBlank 註解所指的 password 字段,表示驗證密碼不能爲空,如果爲空的話,上面 Controller 中的 create 方法會將message 中的"密碼不能爲空"返回。