Spring boot2 path variable validation

416 Views Asked by At

I am using spring boot for creating rest services. I need to validate the parameter passed. I have a service like below,

@GetMapping(value="/employee/{Id}")
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
    ...
}

I need to throw error if Id is not passed in url. Like "Missing Id in request". I was able to achieve using below,

@GetMapping(value={"/employee", "/employee/{Id}"})
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
    ...
}

And handled MissingPathVariableException in ExceptionHandler annotated with @ControllerAdvise.

But I wanted to know is this the right way to check ?

1

There are 1 best solutions below

0
On

You can use @ControllerAdvise to handle exceptions that are generated while executing your actual code.

For Path variable validation, you can make use of spring-boot-starter-validation.

Add this maven dependency:

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

Then your controller will look like:

@GetMapping(value={"/employee", "/employee/{Id}"})
public EmployeeDTO getEmployeeDetails(
    @NotBlank(message = "Missing Id in request")
    @PathVariable String Id) {
    ...
}

I recommend you to read this: Validating Form Input