【问题标题】:Spring Boot: How to make a field as mandatory in POST request while in PUT request it should be optionalSpring Boot:如何在 POST 请求中将字段设为必填,而在 PUT 请求中它应该是可选的
【发布时间】:2018-12-31 03:34:53
【问题描述】:

我正在使用实体类。 考虑在 POST 请求和更新的请求正文中,“名称”字段是强制性的,即在 PUT 请求中,“名称”字段应该是可选的。我们不需要再次传递“名称”字段,这不是必需的。所以我想让“名称”属性在 POST 请求正文中是强制性的,在 PUT 请求正文中是可选的。

【问题讨论】:

  • 使用具有不同验证规则的不同表单对象或使用验证组并为 POST 和 PUT 请求验证不同的对象。

标签: spring-boot annotations entity


【解决方案1】:

您可以在 JSR303 注释中使用 groups 参数。

@NotEmpty 注解适用于通过“现有”接口访问时:

public class Greeting {

  private final long id;
  @NotEmpty(groups = Existing.class)
  private final String content;

  public Greeting(long id, String content) {
      this.id = id;
      this.content = content;
  }

  public long getId() {
      return id;
  }

  public String getContent() {
      return content;
  }

  public interface Existing {
  }
}

注意 PutMapping 上的 @Validated(Existing.class) 注释

@PostMapping("/greeting")
public Greeting newGreeting( @RequestBody Greeting gobj) {
    return new Greeting(counter.incrementAndGet(),
            String.format(template, gobj.getContent()));
}

@PutMapping("/greeting")
public Greeting updateGreeting(@Validated(Existing.class) @RequestBody Greeting gobj) {
    return new Greeting(gobj.getId(),
            String.format(template, gobj.getContent()));
}

对于上面的示例 Json 正文 {"id": 1} 将适用于 POST,但对于 PUT,您将收到 HTTP 400 告诉您“内容参数不能为空”。两种方法都接受{"id": 1, "content":"World"}

【讨论】:

  • 谢谢!这真的很有帮助。
猜你喜欢
  • 2020-11-25
  • 2017-11-11
  • 2018-07-30
  • 2021-01-10
  • 1970-01-01
  • 2019-04-15
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多