0

好的,首先我可以验证用户,如果我正在使用@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;

}
4

1 回答 1

0

只需让 Spring 将 String 解析为 User 并使用相同的 @Valid 注释对其进行注释:

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(@RequestBody @Valid User user) {    
    return new ResponseEntity<String>(user.toJson(), header, HttpStatus.CREATED);
}

甚至

@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<User> createFromJson(@RequestBody @Valid User user) {    
    return new ResponseEntity<User>(user, header, HttpStatus.CREATED);
}
于 2013-10-25T20:59:51.110 回答