In normal usage the HTTP headers in a request message pass along generic information about the message, how it is to be handled in transit, and details about the expected response. While a few standard headers are commonly recognized and used, the HTTP specification allows for any name/value pair to be used as an HTTP header. The JAX-RS APIs provide an easy mechanism for injecting HTTP header information into a resource implementation.
One of the most commonly used HTTP headers is the cookie. Cookies allow HTTP clients and servers to share static information across multiple request/response sequences. The JAX-RS APIs provide an annotation inject data directly from a cookie into a resource implementation.
The 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
Supported data types.
Example 3.6 shows code for injecting the value of the HTTP
If-Modified-Since
header into a class' oldestDate
field.
Example 3.6. Injecting the If-Modified-Since header
import javax.ws.rs.HeaderParam; ... class RecordKeeper { ... @HeaderParam("If-Modified-Since") String oldestDate; ... }
Cookies are a special type of HTTP header. They are made up of one or more name/value pairs that are passed to the resource implementation on the first request. After the first request, the cookie is passes back and forth between the provider and consumer with each message. Only the consumer, because they generate requests, can change the cookie. Cookies are commonly used to maintain session across multiple request/response sequences, storing user settings, and other data that can persist.
The 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
Supported data types, entities decorated with the
@CookieParam
can also be a Cookie
object.
Example 3.7 shows code for injecting the value of the
handle
cookie into a field in the CB
class.
Example 3.7. Injecting a cookie
import javax.ws.rs.CookieParam; ... class CB { ... @CookieParam("handle") String handle; ... }