JAX-RS provides the @Context annotation to inject a variety of resources in your RESTful services. Some of the most commonly injected components are HTTP headers, HTTP URI related information. Here is a complete list (in no specific order)
- HTTP headers
- HTTP URI details
- Security Context
- Resource Context
Lets look at these one by one with the help of examples
Although HTTP headers can be injected using the @HeaderParam annotation, JAX-RS also provides the facility of injecting an instance of the HttpHeaders interface (as an instance variable or method parameter). This is useful when you want to iterate over all possible headers rather than injecting a specific header value by name
HTTP URI details
UriInfo is another interface whose instance can be injected by JAX-RS (as an instance variable or method parameter). Use this instance to fetch additional details related to the request URI and its parameters (query, path)
An instance of the Providers interface can be injected using @Context. One needs to be aware of the fact that this is only valid within an existing provider. A Providers instance enables the current Provider to search for other registered providers in the current JAX-RS container.
Note: Please do not get confused between Provider and Providers.
- A JAX-RS Provider is a is generic term for any class which supplements/extends the JAX-RS features by implementing standard interfaces exposed by the JAX-RS specification
- It is annotated using the @Provider annotation for automatic discovery by the run time
- Examples of JAX-RS providers are – Message Body Reader, Message Body Writer, Exception Mapper and Context Providers.
Refers to the (injectable) javax.ws.rs.ext.Providers interface which was discussed in this sub section
Inject an instance of the javax.ws.rs.core.SecurityContext interface (as an instance variable or method parameter) if you want to gain more insight into identity of the entity invoking your RESTful service. This interface exposes the following information
- Instance of java.security.Principal representing the caller
- Whether or not the user if a part of a specific role
- Which authentication scheme is being used (BASIC/FORM/DIGEST/CERT)
- Whether or not the request invoked over HTTPS
That’s all for this part. Rest of the injectables will be covered in the next iteration.
Until then.. Cheers!