To provide for a more robust service implementation, you may want to ensure that any optional parameters can be set to a default value. This can be particularly useful for values that are taken from query parameters and matrix parameters since entering long URI strings is highly error prone. You may also want to set a default value for a parameter extracted from a cookie since it is possible for a requesting system not have the proper information to construct a cookie with all the values.
The javax.ws.rs.DefaultValue annotation can be used in conjunction with
the following injection annotations:
@PathParam@QueryParam@MatrixParam@FormParam@HeaderParam@CookieParam
The @DefaultValue annotation specifies a default value to be used when the
data corresponding to the injection annotation is not present in the request.
Example 3.9 shows the syntax for using the
@DefaultValue annotation.
Example 3.9. Syntax for setting the default value of a parameter
import javax.ws.rs.DefaultValue;
...
void resourceMethod(@MatrixParam("matrix")
@DefaultValue("value)
int someValue, ... )
...The annotation must come before the parameter, bean, or field, it will effect. The position of the
@DefaultValue annotation relative to the accompanying injection annotation
does not matter.
The @DefaultValue annotation takes a single parameter. This parameter is
the value that will be injected into the field if the proper data cannot be extracted based on the
injection annotation. The value can be any String value. The value should be compatible with
type of the associated field. For example, if the associated field is of type int, a default
value of blue results in an exception.
If the type of the annotated parameter, bean or field is List,
Set, or SortedSet then the resulting collection
will have a single entry mapped from the supplied default value.
Example 3.10 shows two examples of using the
@DefaultValue to specify a default value for a field whose value is
injected.
Example 3.10. Setting default values
import javax.ws.rs.DefaultValue; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/monster") public class MonsterService { @Get public Monster getMonster(@QueryParam("id") @DefaultValue("42") int id, @QueryParam("type") @DefaultValue("bogeyman") String type) { ... } ... }
The getMonster() method in Example 3.10 is
invoked when a GET request is sent to
. The method expects two query parameters,
baseURI/monsterid and type, appended to the URI. So a GET
request using the URI would return
the Fomóiri with the id of one.baseURI/monster?id=1&type=fomóiri
Because the @DefaultValue annotation is placed on both parameters, the
getMonster() method can function if the query parameters are omitted. A
GET request sent to is
equivalent to a baseURI/monsterGET request using the URI
.baseURI/monster?id=42&type=bogeyman








