Spring - checking path variable for null at controller

Viewed 3825

I define a path variable at controller Get request using:

@PathVariable("ticketId") final Long ticketId

How can I check this value is not null ?

Reading https://www.baeldung.com/spring-validate-requestparam-pathvariable @NotBlank is utilised but checking for null is not mentioned.

Using:

if ticketId == Null {
//return message indicating to user that null has been passed to path
}

Seems a bad practice and instead try/catch should be used ?

2 Answers

You can use the annotation @NotNull which validates the passed parameter is not null. However, it works only for the object types like Long. In case you use a primitive data type long, the annotation cannot be used.

@PathVariable("ticketId") @NotNull final Long ticketId

I rather recommend to use long which cannot be null by definition.

Alternatively, you can throw ResponseStatusException if there is more advanced logic of validating the incoming parameters. The advantage of this approach is that the HTTP status is propagated to the final response. The following sample results in 400 Bad Request:

if (ticketId == null) {
    throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ticketId cannot be null");
}

Use @NotBlank for String datatypes and @NotNull for other Wrapper Types but for Primitve types it wont work as they wont return null as they have a default value.

Related