【问题标题】:Annotation Validation注释验证
【发布时间】:2013-10-25 20:54:08
【问题描述】:

好的,如果我使用 @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;

}

【问题讨论】:

  • 您也可以使用@Valid 注释@RequestBody 注释参数。
  • @Valid json 字符串? (@RequestBody@ValidString json)但我想要验证用户对象

标签: json spring validation annotations


【解决方案1】:

只需让 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);
}

【讨论】:

  • 但是怎么做呢? spring 不会只是将 json 字符串解析为 User 对象,我需要做什么才能使其工作?
  • 我不确定我错过了什么。我收到错误消息 - 服务器拒绝此请求,因为请求实体的格式不受所请求方法的请求资源支持()
  • 您必须在类路径中有 Jackson JSON 映射器。请参阅本文档中的 docs.spring.io/spring/docs/3.2.4.RELEASE/… 和 grep "Jackson"。
  • 有什么例子吗?我发现的只是返回 Json 而不是接收?看来我错过了一些简单的东西,但我无法谷歌!任何具有配置的工作示例将不胜感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-05
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多