Rolando
Rolando

Reputation: 62596

Can you have an optional QueryParam in jersey?

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?

Upvotes: 11

Views: 32010

Answers (3)

charlie_pl
charlie_pl

Reputation: 3074

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

Upvotes: 3

rafikn
rafikn

Reputation: 383

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

Upvotes: 21

rgettman
rgettman

Reputation: 178253

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.

Upvotes: 11

Related Questions