[英]Spring MVC nested object validation
I have the following code in my controller 我的控制器中有以下代码
@RequestMapping(value = "employee/update", method = RequestMethod.POST, headers = "Accept=application/json")
public UpdateEmployeeResponse updateEmployee(@RequestBody @Valid @ModelAttribute("updateEmployeeRequest") UpdateEmployeeRequest updateEmployeeRequest, BindingResult result) {
My Request object is as follows 我的Request对象如下
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
public class Employee {
@NotNull
protected String id;
@NotNull
protected String name;
.
.
When I send JSON request like (id is missing) 当我发送JSON请求时(id丢失)
{employee:{name:"cc",phone:"9876543210",dept:"dpt"}}
My Request is not getting validated by spring(it doesn't show any error even if a field is missing). 我的请求未通过spring验证(即使缺少字段也不显示任何错误)。 I have gone through the following threads but no luck. 我已经完成了以下线程,但没有运气。
Can anyone help? 有人可以帮忙吗?
To ignore any unknown properties in JSON input without exception try using @JsonIgnoreProperties(ignoreUnknown=true)
. 要毫无异常地忽略JSON输入中的任何未知属性,请尝试使用@JsonIgnoreProperties(ignoreUnknown=true)
。
Try this out 试试吧
Employee.java Employee.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee
{
@NotNull
protected String id;
@NotNull
protected String name;
.
.
UpdateEmployeeRequest.java UpdateEmployeeRequest.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class UpdateEmployeeRequest {
@Valid
@NotNull
private Employee employee;
.
.
You don't mention whether you have a validator in the project. 您没有提到项目中是否有验证器。 In Maven add these dependencies: 在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.