44.2. Using JAX-RS APIs
44.2.1. JAX-RS Annotation Types
44.2.2. Injecting data from a request URI
Overview
Getting data from the URI's path
javax.ws.rs.PathParam
annotation. The @PathParam
annotation has a single parameter that identifies the URI template variable from which the data will be injected.
@PathParam
annotation specifies that the value of the URI template variable color
is injected into the itemColor
field.
Example 44.1. Injecting data from a URI template variable
import javax.ws.rs.Path; import javax.ws.rs.PathParam ... @Path("/boxes/{shape}/{color}") class Box { ... @PathParam("color") String itemColor; ... }
@PathParam
annotation are different from the ones described in the section called “Supported data types”. The entity into which the @PathParam
annotation injects data must be of one of the following types:
PathSegment
The value will be the final segment of the matching part of the path.List<PathSegment>
The value will be a list ofPathSegment
objects corresponding to the path segment(s) that matched the named template parameter.- primitives such as int, char, or long
- Objects that have a constructor that accepts a single String argument
- Objects that have a static
valueOf()
method that accepts a single String argument
Using query parameters
?
). They consist of one, or more, name value pairs where the name and value are separated by an equal sign(=
). When more than one query parameter is specified, the pairs are separated from each other by either a semicolon(;
) or an ampersand(&
). Example 44.2, “URI with a query string” shows the syntax of a URI with query parameters.
Example 44.2. URI with a query string
http://fusesource.org?name=value;name2=value2;...
javax.ws.rs.QueryParam
annotation extracts the value of a query parameter and injects it into a JAX-RS resource. The annotation takes a single parameter that identifies the name of the query parameter from which the value is extracted and injected into the specified field, bean property, or parameter. The @QueryParam
annotation supports the types described in the section called “Supported data types”.
id
into the method's id
parameter.
Example 44.3. Resource method using data from a query parameter
import javax.ws.rs.QueryParam; import javax.ws.rs.PathParam; import javax.ws.rs.POST; import javax.ws.rs.Path; ... @Path("/monstersforhire/") public class MonsterService { ... @POST @Path("/{type}") public void updateMonster(@PathParam("type") String type, @QueryParam("id") String id) { ... } ... }
POST
to /monstersforhire/daikaiju?id=jonas the updateMonster()
method's type
is set to daikaiju
and the id
is set to jonas
.
Using matrix parameters
;
). /mostersforhire/daikaiju;id=jonas has one matrix parameter called id
and /monstersforhire/japan;type=daikaiju/flying;wingspan=40 has two matrix parameters called type
and wingspan
.
javax.ws.rs.MatrixParam
annotation. The annotation takes a single parameter that identifies the name of the matrix parameter from which the value is extracted and injected into the specified field, bean property, or parameter. The @MatrixParam
annotation supports the types described in the section called “Supported data types”.
type
and id
into the method's parameters.
Example 44.4. Resource method using data from matrix parameters
import javax.ws.rs.MatrixParam; import javax.ws.rs.POST; import javax.ws.rs.Path; ... @Path("/monstersforhire/") public class MonsterService { ... @POST public void updateMonster(@MatrixParam("type") String type, @MatrixParam("id") String id) { ... } ... }
POST
to /monstersforhire;type=daikaiju;id=whale the updateMonster()
method's type
is set to daikaiju
and the id
is set to whale
.
Disabling URI decoding
javax.ws.rs.Encoded
annotation to deactivate the URI decoding. The annotation can be used to deactivate URI decoding at the following levels:
- class level—Decorating a class with the
@Encoded
annotation deactivates the URI decoding for all parameters, field, and bean properties in the class. - method level—Decorating a method with the
@Encoded
annotation deactivates the URI decoding for all parameters of the class. - parameter/field level—Decorating a parameter or field with the
@Encoded
annotation deactivates the URI decoding for all parameters of the class.
getMonster()
method does not use URI decoding. The addMonster()
method only disables URI decoding for the type
parameter.
Example 44.5. Disabling URI decoding
@Path("/monstersforhire/") public class MonsterService { ... @GET @Encoded @Path("/{type}") public Monster getMonster(@PathParam("type") String type, @QueryParam("id") String id) { ... } @PUT @Path("/{id}") public void addMonster(@Encoded @PathParam("type") String type, @QueryParam("id") String id) { ... } ... }
Error handling
WebApplicationException
exception wrapping the original exception is generated. The WebApplicationException
exception's status is set to 404
.
44.2.3. Injecting data from the HTTP message header
Overview
Injecting information from the HTTP headers
javax.ws.rs.HeaderParam
annotation is used to inject the data from an HTTP header field into a parameter, field, or bean property. It has a single parameter that specifies the name of the HTTP header field from which the value is extracted and injected into the resource implementation. The associated parameter, field, or bean property must conform to the data types described in the section called “Supported data types”.
If-Modified-Since
header into a class' oldestDate
field.
Example 44.6. Injecting the If-Modified-Since header
import javax.ws.rs.HeaderParam; ... class RecordKeeper { ... @HeaderParam("If-Modified-Since") String oldestDate; ... }
Injecting information from a cookie
javax.ws.rs.CookieParam
annotation extracts the value from a cookie's field and injects it into a resource implementation. It takes a single parameter that specifies the name of the cookie's field from which the value is to be extracted. In addition to the data types listed in the section called “Supported data types”, entities decorated with the @CookieParam
can also be a Cookie
object.
handle
cookie into a field in the CB
class.
Example 44.7. Injecting a cookie
import javax.ws.rs.CookieParam; ... class CB { ... @CookieParam("handle") String handle; ... }
Error handling
WebApplicationException
exception wrapping the original exception is generated. The WebApplicationException
exception's status is set to 400
.
44.2.4. Injecting data from HTML forms
Overview
GET
requests and HTTP POST
requests:
- GET
- When form data is sent as part of an HTTP
GET
request the data is appended to the URI as a set of query parameters. Injecting data from query parameters is discussed in the section called “Using query parameters”. - POST
- When form data is sent as part of an HTTP
POST
request the data is placed in the HTTP message body. The form data can be handled using a regular entity parameter that supports the form data. It can also be handled by using the@FormParam
annotation to extract the data and inject the pieces into resource method parameters.
Using the @FormParam annotation to inject form data
javax.ws.rs.FormParam
annotation extracts field values from form data and injects the value into resource method parameters. The annotation takes a single parameter that specifies the key of the field from which it extracts the values. The associated parameter must conform to the data types described in the section called “Supported data types”.
@FormParam
annotation can be placed on fields, methods, and parameters. However, the @FormParam
annotation is only meaningful when placed on resource method parameters.
Example
title
, tags
, and body
—that contain string data.
Example 44.8. Injecting form data into resource method parameters
import javax.ws.rs.FormParam; import javax.ws.rs.POST; ... @POST public boolean updatePost(@FormParam("title") String title, @FormParam("tags") String tags, @FormParam("body") String post) { ... }
44.2.5. Specifying a default value to inject
Overview
javax.ws.rs.DefaultValue
annotation can be used in conjunction with the following injection annotations:
@PathParam
@QueryParam
@MatrixParam
@FormParam
@HeaderParam
@CookieParam
@DefaultValue
annotation specifies a default value to be used when the data corresponding to the injection annotation is not present in the request.
Syntax
@DefaultValue
annotation.
Example 44.9. Syntax for setting the default value of a parameter
import javax.ws.rs.DefaultValue; ... void resourceMethod(@MatrixParam("matrix") @DefaultValue("value) int someValue, ... ) ...
@DefaultValue
annotation relative to the accompanying injection annotation does not matter.
@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.
Dealing with lists and sets
List
, Set
, or SortedSet
then the resulting collection will have a single entry mapped from the supplied default value.
Example
@DefaultValue
to specify a default value for a field whose value is injected.
Example 44.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) { ... } ... }
getMonster()
method in Example 44.10, “Setting default values” is invoked when a GET
request is sent to baseURI/monster. The method expects two query parameters, id
and type
, appended to the URI. So a GET
request using the URI baseURI/monster?id=1&type=fomóiri would return the Fomóiri with the id of one.
@DefaultValue
annotation is placed on both parameters, the getMonster()
method can function if the query parameters are omitted. A GET
request sent to baseURI/monster is equivalent to a GET
request using the URI baseURI/monster?id=42&type=bogeyman.
44.2.6. Injecting Parameters into a Java Bean
Overview
@FormParam
annotations to its method parameters), and the resource method then calls the bean's constructor, passing in the form data.
@BeanParam
annotation, it is possible to implement this pattern in a single step. The form data can be injected directly into the fields of the bean class and the bean itself is created automatically by the JAX-RS runtime. This is most easily explained by example.
Injection target
@BeanParam
annotation can be attached to resource method parameters, resource fields, or bean properties. A parameter target is the only kind of target that can be used with all resource class lifecycles, however. The other kinds of target are restricted to the per-request lifecycle. This situation is summarized in Table 44.1, “@BeanParam Injection Targets”.
Target | Resource Class Lifecycles |
---|---|
PARAMETER | All |
FIELD | Per-request (default) |
METHOD (bean property) | Per-request (default) |
Example without BeanParam annotation
@BeanParam
):
// Java import javax.ws.rs.POST; import javax.ws.rs.FormParam; import javax.ws.rs.core.Response; ... @POST public Response orderTable(@FormParam("orderId") String orderId, @FormParam("color") String color, @FormParam("quantity") String quantity, @FormParam("price") String price) { ... TableOrder bean = new TableOrder(orderId, color, quantity, price); ... return Response.ok().build(); }
orderTable
method processes a form that is used to order a quantity of tables from a furniture Web site. When the order form is posted, the form values are injected into the parameters of the orderTable
method, and the orderTable
method explicitly creates an instance of the TableOrder
class, using the injected form data.
Example with BeanParam annotation
@BeanParam
annotation. When using the @BeanParam
approach, the form parameters can be injected directly into the fields of the bean class, TableOrder
. In fact, you can use any of the standard JAX-RS parameter annotations in the bean class: including @PathParam
, @QueryParam
, @FormParam
, @MatrixParam
, @CookieParam
, and @HeaderParam
. The code for processing the form can be refactored as follows:
// Java import javax.ws.rs.POST; import javax.ws.rs.FormParam; import javax.ws.rs.core.Response; ... public class TableOrder { @FormParam("orderId") private String orderId; @FormParam("color") private String color; @FormParam("quantity") private String quantity; @FormParam("price") private String price; // Define public getter/setter methods // (Not shown) ... } ... @POST public Response orderTable(@BeanParam TableOrder orderBean) { ... // Do whatever you like with the 'orderBean' bean ... return Response.ok().build(); }
@FormParam
annotations in the signature of the resource method with just a single @BeanParam
annotation, as shown. Now, when the form is posted to the orderTable
resource method, the JAX-RS runtime automatically creates a TableOrder
instance, orderBean
, and injects all of the data specified by the parameter annotations on the bean class.