2

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
  • You can use @NotNull for null Checking Commented Apr 7, 2020 at 17:07
  • If(StringUtils.isNotEmpty(ticketId)) should suffice Commented Apr 7, 2020 at 17:08

3 Answers 3

6

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");
}
Sign up to request clarification or add additional context in comments.

1 Comment

I rather recommend using long which cannot be null by definition. +1
0

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.

Comments

0

In Spring, method parameters annotated with @PathVariable are required by default. You don't need to annotate @NotNull. However, you can use @Positive / @PositiveOrZero annotations. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html#:~:text=%22%22-,required,-boolean%C2%A0required

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.