10

Using java jersey, I have the following @QueryParam's in my method handler:

@Path("/hello")
handleTestRequest(@QueryParam String name, @QueryParam Integer age)

I know if I do: http://myaddress/hello?name=something

It will go into that method....

I want to make it so that I can call:

http://myaddress/hello?name=something

And it will also go into that same method. Is there any way I can flag an "optional" PathParam? Does it work with @FormParam too? Or am I required to create a separate method with a different method signature?

3 Answers 3

19

In JAX-RS parameters are not mandatory, so if you do not supply an age value, it will be NULL, and your method will still be called.

You can also use @DefaultValue to provide a default age value when it's not present.

The @PathParam parameter and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, and @FormParam obey the same rules as @QueryParam.

Reference

1
  • 6
    Looks like jersey 2.23 returns 404 by default in case a queryParameter is not passed. So is it not exactly following the spec?
    – nikel
    Oct 12, 2016 at 9:08
10

You should be able to add the @DefaultValue annotation the age parameter, so that if age isn't supplied, the default value will be used.

@Path("/hello")
handleTestRequest(
    @QueryParam("name") String name,
    @DefaultValue("-1") @QueryParam("age") Integer age)

According to the Javadocs for @DefaultValue, it should work on all *Param annotations.

Defines the default value of request meta-data that is bound using one of the following annotations: PathParam, QueryParam, MatrixParam, CookieParam, FormParam, or HeaderParam. The default value is used if the corresponding meta-data is not present in the request.

3

You can always wrap return type in optional, for example: @QueryParam("from") Optional<String> from

2
  • 3
    Such solution does not work for me. Got ModelValidationException in the result
    – Tioma
    Dec 27, 2018 at 12:29
  • This doesn't work out-of-the-box, you have to find some code to support Optionals: stackoverflow.com/a/65148523/5209935
    – Matthew
    Dec 4, 2020 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.