英文:
Need to Reject POST/PUT request if any unknown field is present in RequestBody
问题
@Valid 检查对应字段是否有效。是否有办法在POST/PUT请求的JSON请求体中存在未知字段时拒绝请求?以下是我的示例DTO类和控制器。
对于下面的示例请求体(例如),请求应该被拒绝/抛出异常。
任何帮助或建议将不胜感激。
{
"accountid" : "P12345",
"name" : "Cardiology",
"domain" : "Apollo"
}
public class Account {
@NotEmpty(message = "accountid is required")
private String accountid;
@NotEmpty(message = "name is required")
private String name;
// getters & setters
}
public class BeanController {
@PostMapping(path = "/accounts")
public ResponseEntity<?> getAllAccounts(@RequestBody @Valid Account account) {
System.out.println("::: Account is " + account + " :::");
return ResponseEntity.ok().body("SUCCESS");
}
}
英文:
@Valid check is working for respective fields. Is there any way to reject requests if any unknown fields are present in JSON requestbody of POST/PUT requests.Below is my sample DTO class and controller.
For below sample request body (for example), the request should be rejected/throw exception.
Any help or suggestion would be appreciated.
{
"accountid" : "P12345",
"name" : "Cardiology",
"domain" : "Apollo"
}
public class Account {
@NotEmpty(message = "accountid is required")
private String accountid;
@NotEmpty(message = "name is required")
private String name;
//getters & setters
}
**********************************************************************************************
public class BeanController {
@PostMapping(path = "/accounts")
public ResponseEntity<?> getAllAccounts(@RequestBody @Valid Account account) {
System.out.println("::: Account is " + account + " :::");
return ResponseEntity.ok().body("SUCCESS");
}
}
答案1
得分: 6
你可以通过使用 @JsonIgnoreProperties
来实现。
@JsonIgnoreProperties(ignoreUnknown = false)
public class Account {
@NotEmpty(message = "accountid is required")
private String accountid;
@NotEmpty(message = "name is required")
private String name;
//getters & setters
}
在 application.yml
中添加以下属性以在最新版本的 spring-boot 中工作。
spring:
jackson:
deserialization:
fail-on-unknown-properties: true
英文:
You can do it by using @JsonIgnoreProperties
.
@JsonIgnoreProperties(ignoreUnknown = false)
public class Account {
@NotEmpty(message = "accountid is required")
private String accountid;
@NotEmpty(message = "name is required")
private String name;
//getters & setters
}
Add below properties in application.yml to working in spring-boot latest version.
spring:
jackson:
deserialization:
fail-on-unknown-properties: true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论