Validate Additional parameters in Requestbody for Springboot request and throw 400

420 Views Asked by At
@Data
public class Employee{
@NotNull
@NotBlank
private string id;

@NotNull
@NotBlank
private string name;
}

@RestController
@Validated
class EmployeeController{

@postMapping(consumes="json", produces="json")
public ResponseEntity getEmployee(@Valid @RequestBody Employee){
 return response;
}

}

Added Exceptional Handler with MethodArgumentNotvalidException.

positive Validation works fine, Whenever we check with id & name.

Expectation is, if we add any additional parameters along with id and name, it should throw the 400

sample input : { "abc":"xyz", "id":"09e240", "name":"Billa" }

Expected Output : 400 bad request
1

There are 1 best solutions below

0
On

The validation doesn't occur until after the deserialization into the Employee object has occurred; therefore, I don't believe you can do this with the validation API.

What you want to do is force the deserialization to fail on unknown properties. Create a bean of type ObjectMapper and configure it to fail deserialization when it encounters unknown properties.

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    return objectMapper;
}

This will throw an UnrecognizedPropertyException, then you can use ControllerAdvice to map this to a 400. By the way, I suspect that you have already created this bean somewhere as the default behavior for ObjectMapper is set to FAIL_ON_UNKNOWN_PROPERTIES -> true.

The controller advice to map the UnrecognizedPropertyException will look like this:

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


@ControllerAdvice
public class Advice {

    @ExceptionHandler(UnrecognizedPropertyException.class)
    public ResponseEntity<?> handleDeserializationErrors(UnrecognizedPropertyException unrecognizedPropertyException) {
        return ResponseEntity.badRequest().body(unrecognizedPropertyException.getMessage());
    }
}