0

the request body contains data as below { "name":"hi", "age":10, "hi":"" }

But In Rest Controller I'm trying to get those data with the help of DTO, RestControllerDTO.class

public RestControllerDTO {

@Notblank private String name;

@Notblank private Integer age;

// getter and setters

}

Now I want to throw an exception as "hi" is an unknown field before entering into the controller class.

vicky
  • 43
  • 1
  • 7
  • Can you elaborate on what you want to do exactly? – Karthik Chennupati Jul 20 '20 at 17:32
  • 1
    if you are using jackson for json deserialization, try setting `spring.jackson.deserialization.fail-on-unknown-properties=true` in *application.properties*, [source](https://stackoverflow.com/a/44901823/13527856) – MarcoLucidi Jul 20 '20 at 17:45

1 Answers1

1

You do this by using @Valid annotation in your controller method

@GetMapping("/foo")
public void bar(@Valid RestControllerDTO dto, BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        throw new Exception();
    }
...

https://spring.io/guides/gs/validating-form-input/

I would also suggest adding @NotNull as @NotBlank only checks for ""

J Asgarov
  • 2,526
  • 1
  • 8
  • 18