好的,首先我可以验证用户,如果我正在使用@Valid
并且传入的是User
实例而不是 json 字符串。这很好用,例如:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
userRep.save(user);
return "redirect:/";
}
所以问题是如何创建某种 API 并且传入的是 Json 字符串,并自动验证注释,例如@Email
,@NotEmpty
?最佳做法是什么?
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody String json) {
User user = User.fromJsonToUser(json);
return new ResponseEntity<String>(user.toJson(),header,HttpStatus.CREATED);
}
用户类
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty
@Length(max = 30)
private String firstName;
@Email
@NotEmpty
@Length(min = 3 , max = 50)
private String primaryEmail;
}