3

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

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)

{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). I have gone through the following threads but no luck.

Can anyone help?

1
  • 1
    Please add the htmpl form code. Commented Dec 21, 2015 at 13:57

2 Answers 2

1

To ignore any unknown properties in JSON input without exception try using @JsonIgnoreProperties(ignoreUnknown=true).

Try this out

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;
 .
 .
Sign up to request clarification or add additional context in comments.

5 Comments

My question is the validation itself is not working. I want to make it work.
@arjuncc you mean validation fails during deserializing json to java
exactly, i dont have any error in when i check hasError method in BindingResult.
@arjuncc can you post your jsp page
The question has nothing to do with ignoring properties or jsp (or other) front-end code. The question is why aren't nested object properties having their @NotNull validation checked on the server side when it receives a JSON request. I'm having the same problem.
0

You don't mention whether you have a validator in the project. In Maven add these dependencies:

        <!-- 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.