1

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?

fxvlad
  • 129
  • 2
  • 3
  • 9
  • It seems that the question is related to custom validation in request parameters. If so, it is an asked and well answered [question](https://stackoverflow.com/questions/59422883/spring-boot-custom-validation-in-request-params). – Tonny Tc Oct 19 '21 at 02:53

1 Answers1

0

@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

  • I need to use many annotations on each param with this and and the code gets look bad and unclear (looks like a bad way). And when you use the annotation for validation with RequestParam annotation (not RequestBody) you have to use Validated annotation on your class and it throws ConstraintViolationException and caused 500 error when the params are not passed the validation – fxvlad Oct 19 '21 at 12:06