Spring MVC 嵌套对象验证
Spring MVC nested object validation
我的控制器中有以下代码
@RequestMapping(value = "employee/update", method = RequestMethod.POST, headers = "Accept=application/json")
public UpdateEmployeeResponse updateEmployee(@RequestBody @Valid @ModelAttribute("updateEmployeeRequest") UpdateEmployeeRequest updateEmployeeRequest, BindingResult result) {
我的请求对象如下
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
public class Employee {
@NotNull
protected String id;
@NotNull
protected String name;
.
.
当我发送 JSON 请求时(id 丢失)
{employee:{name:"cc",phone:"9876543210",dept:"dpt"}}
我的请求未通过 spring 验证(即使缺少字段也不会显示任何错误)。我已经完成了以下线程,但没有运气。
- link1
- link2
有人能帮忙吗?
要无一例外地忽略 JSON 输入中的任何未知属性,请尝试使用 @JsonIgnoreProperties(ignoreUnknown=true)
。
试试这个
Employee.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee
{
@NotNull
protected String id;
@NotNull
protected String name;
.
.
UpdateEmployeeRequest.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
你没有提到项目中是否有验证器。在 Maven 中添加这些依赖项:
<!-- Bean validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
我的控制器中有以下代码
@RequestMapping(value = "employee/update", method = RequestMethod.POST, headers = "Accept=application/json")
public UpdateEmployeeResponse updateEmployee(@RequestBody @Valid @ModelAttribute("updateEmployeeRequest") UpdateEmployeeRequest updateEmployeeRequest, BindingResult result) {
我的请求对象如下
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
public class Employee {
@NotNull
protected String id;
@NotNull
protected String name;
.
.
当我发送 JSON 请求时(id 丢失)
{employee:{name:"cc",phone:"9876543210",dept:"dpt"}}
我的请求未通过 spring 验证(即使缺少字段也不会显示任何错误)。我已经完成了以下线程,但没有运气。
- link1
- link2
有人能帮忙吗?
要无一例外地忽略 JSON 输入中的任何未知属性,请尝试使用 @JsonIgnoreProperties(ignoreUnknown=true)
。
试试这个
Employee.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee
{
@NotNull
protected String id;
@NotNull
protected String name;
.
.
UpdateEmployeeRequest.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
你没有提到项目中是否有验证器。在 Maven 中添加这些依赖项:
<!-- Bean validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>