vicky
vicky

Reputation: 53

How to validate unwanted request body parameters for POST method in Rest API in Spring Boot

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.

Upvotes: 0

Views: 931

Answers (1)

asgarov1
asgarov1

Reputation: 4098

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

Upvotes: 1

Related Questions