How to correct validate parameters from GET request in Spring Boot?

Viewed 326

I have a GET handler where I get 3 parameters from the URL with @RequestParam annotation:

@GetMapping
public String getStocks(@RequestParam(value = "color", required = true) String color,
                        @RequestParam(value = "op", required = true) String op,
                        @RequestParam(value = "size", required = true) Integer size) {

    return service.getStocks(color, op, size);
}

and I need to do a lot of validations on each of these params e.g. matching regex pattern, range, etc. I can't do it on the frontend.
I tried to do that with annotations right before @RequestParam and that works but it looks so ugly and messy cause I need add lots of them on each parameter.

Is there "the right way" to validate params from GET request like we can do it with DTO with POST request?

1 Answers

@RequestParam(value = "color", required = true) String color Don't need to use required = true, by default it is true, you need to specify it when required = false.

You can use the following dependency to validate input.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Can use like this.

@RequestParam("size") @Min(5) int size

Related