Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have an optional QueryParam in jersey?

Tags:

java

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?

like image 736
Rolando Avatar asked Sep 02 '15 21:09

Rolando


Video Answer


2 Answers

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

like image 172
rafikn Avatar answered Oct 12 '22 23:10

rafikn


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.

like image 38
rgettman Avatar answered Oct 13 '22 01:10

rgettman