Context providers supply a context object to resource classes or to other providers.
A context provider class must implement the ContextResolver<T>interface.
The implementation should be annotated with @Provider for automatic discovery or we can programmatically register it too.
Context provider implementations may restrict the media types they support using the @Produces annotation. The absence of this annotation implies that any media type is supported.
On the usage side (a resource class/method or another provider), we have to inject Providers with @Context annotation to access our context.
Let's see how to write and use a context provider.
Example
In this very simple example, we are focusing on how to use context provider feature rather than implementing a meaningful context object.
Writing a Context Provider
public interface MyContext<T> {
T get(String key);
}
Now we are going to implement ContextProvider interface which requires only one method to implement: getContext(Class<?> type) :
@Provider
public class MyContextResolver implements
ContextResolver<MyContext> {
private MyContext context = new MyContextImpl();
@Override
public MyContext getContext(Class<?> type) {
if (type == String.class) {
return context;
}
return null;
}
private static class MyContextImpl implements MyContext<String> {
@Override
public String get(String key) {
return "a context value for key=" + key;
}
}
}
Writing a Resource
@Path("/")
public class MyResource {
@GET
@Path("{path}")
public String create(@PathParam("path") String path,
@Context Providers providers) {
ContextResolver<MyContext> cr = providers
.getContextResolver(MyContext.class, MediaType.WILDCARD_TYPE);
MyContext<String> c = cr.getContext(String.class);
String r = c.get(path);
return "response: " + r;
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Writing a JAX-RS client
public class JaxRsClient {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget baseTarget = client.target("http://localhost:8080/example");
String response = baseTarget.request()
.get(String.class);
System.out.println(response);
}
} Outputresponse: a test context value for key=example
In the next example, we will see a more practical example. We will also learn how to access a ContextResolver in another provider (a class annotated with @Provider).
Example ProjectDependencies and Technologies Used: - jersey-server 2.25.1: Jersey core server implementation.
- jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
- JDK 1.8
- Maven 3.3.9
|