我正在使用实体类。 考虑在 POST 请求和更新的请求正文中,字段“名称”是必需的,即在 PUT 请求中,“名称”字段应该是可选的。我们不需要再次传递“名称”字段,这是没有必要的。所以我想在 POST 请求正文中强制设置“Name”属性,在 PUT 请求正文中设置为可选属性。
最佳答案
您可以在 JSR303 注释中使用组参数。
@NotEmpty 注释适用于通过“现有”接口(interface)访问时:
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"}
将被两种方法接受。
关于spring-boot - Spring 启动 : How to make a field as mandatory in POST request while in PUT request it should be optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979988/