Home > Back-end >  Spring Boot @PostMapping is there a way to detect null fields in a incoming request body?
Spring Boot @PostMapping is there a way to detect null fields in a incoming request body?

Time:09-27

In Spring Boot @PostMapping is there a way to detect null fields in an incoming request body before mapping the request body into a particular class?

My post mapping is like this,

  @PostMapping("/post")
    public ResponseEntity<User> insertFromBody(
            @Valid @RequestBody  User user) {
        //call service class
}

User Class

@Entity
@Table(name="Users")
public class User {
    @Id
    @JsonProperty("USER")
    @Column(name = "USER")
    private String userId;

    @JsonProperty("FIRST_NAME")
    @Column(name = "FIRST_NAME")
    private String firstname;

    @JsonProperty("LAST_NAME")
    @Column(name = "LAST_NAME")
    private String lastname;
    
    @JsonProperty("AGE")
    @Column(name = "AGE")
    private String age;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

Request body may be as below,

1st type
{
   "ID":1,
   "FIRST_NAME":"JOHN"
}

2nd type
{
   "ID":1,
   "FIRST_NAME":"JOHN",
   "LAST_NAME":null,
   "AGE":null
}

So before mapping request body to the User object is there a way to detect null fields? (want to differentiate between request type 1 and 2)

CodePudding user response:

  1. add dependency "org.springframework.boot:spring.boot.starter.validation"
  2. add @NotNull to not-null field
  3. add @Valid

CodePudding user response:

Yehh use @NotNull and @Valid, it's going to throw an exception so I recommend to use an exception handler to format the message. Here is an article how to use Validator

  • Related