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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With