Search code examples
javarestjavax.ws.rsquery-string

What are the default values for @QueryParam when @DefaultValue is not specified?


For example, having the following Java rest definition:

@GET
@Path("/something")
public String somthing(
    @QueryParam("valString") String valString,
    @QueryParam("valInt") int valInt,
    @QueryParam("valBool") boolean valBool
) {
  ...
}

And invocation:

curl -X GET 127.0.0.1/something

What will the parameters values be if not specified in the invocation? (valString=?, valInt=?, valBool=?)


Solution

  • Short answer

    The parameter values will be:

    • valString: null
    • valInt: 0
    • valBool: false

    A bit longer answer

    Quoting the Java EE 7 tutorial about extracting request parameters:

    If @DefaultValue is not used in conjunction with @QueryParam, and the query parameter is not present in the request, the value will be an empty collection for List, Set, or SortedSet; null for other object types; and the default for primitive types.

    The default values for primitive types are described in the Java Tutorials from Oracle:

     Primitive       Default Value
    -------------------------------
     byte            0
     short           0
     int             0
     long            0L
     float           0.0f
     double          0.0d
     char            '\u0000'
     boolean         false
    

    As you already know, this behavior can be changed by using the @DefaultValue annotation as following:

    @GET
    @Path("/foo")
    public String myMethod(@DefaultValue("foo") @QueryParam("valString") String valString,
                           @DefaultValue("1") @QueryParam("valInt") int valInt,
                           @DefaultValue("true") @QueryParam("valBool") boolean valBool) {
        ....
    }