What objects can I inject using the @Context annotation?
Asked Answered
P

4

43

I'm new to JAX-RS and I'm trying to understand how the @Context annotation is supposed to work.

At the javadoc there is a list of six classes (Application, UriInfo, Request, HttpHeaders, SecurityContext, Providers). However I find code on the web that use the this annotation with other types, for example:

@GET
public String something(@Context HttpServletRequest req) {

}

Is there a list of supported types that can be used with this annotations? Does this list change between implementation of the standard?

I'm currently experimenting with Jersey and I'm worried that I'll write code that cannot be ported to other JAX-RS implementation.

Pahl answered 5/1, 2014 at 18:22 Comment(1)
I believe it's up to the implementation. There's a provider (I don't know the exact name of the implementation) that resolve the parameter type and generates an appropriate argument to use.Seism
L
26

The riveting JAX-RS specification defines all the standard types you can inject via @Context.

But if I were you, I would just consult the specific documentation of your chosen provider to see what is available.

For example, RESTEasy provides these values via @Context. Meanwhile, Jersey provides these. Obviously there will be overlap because of the standard context values.

Lati answered 5/1, 2014 at 19:27 Comment(3)
Thanks for the response. For anyone else interested, the correct link for the specification: download.oracle.com/otndocs/jcp/jaxrs-2_0-fr-eval-spec/… (you need to accept the license first)Pahl
The link I provided was correct, but it did have an "AuthParam" after I accepted the license as you say. The edited link without that query parameter should work just fine.Lati
Relevant link to the Jersey user guide. Quote: "These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation."Dripps
W
75

The @Context annotation allows you to inject request/response context details into JAX-RS provider and resource classes. Injection can be performed into a class field, a bean property or a method parameter.


The following list summarizes all the types that can be injected using the @Context annotation, according to the JAX-RS 2.0 specification:

Except for Configuration and Providers, which are injectable in both client and server-side providers, all the other types are server-side only.

The following types are available only when the application is deployed in a servlet container:

JAX-RS 2.1 introduced other types that can be injected with @Context:

Besides the standard types listed above, JAX-RS implementations, such as Jersey, RESTEasy and Apache CXF, might define their own types that can be injected using @Context.


Find below a quick description of each JAX-RS type available for injection:

  • Application: The instance of the application-supplied Application subclass can be injected into a class field or method parameter. Access to the Application subclass instance allows configuration information to be centralized in that class.

  • URIs and URI templates: UriInfo provides both static and dynamic, per-request information, about the components of a request URI.

  • Headers: HttpHeaders provides access to request header information either in map form or via strongly typed convenience methods. Response headers may be provided using the Response class.

  • Content negotiation and preconditions: The methods of Request allow a caller to determine the best matching representation variant and to evaluate whether the current state of the resource matches any preconditions in the request.

  • Security context: The SecurityContext interface provides access to information about the security context of the current request. The methods of SecurityContext provide access to the current user principal, information about roles assumed by the requester, whether the request arrived over a secure channel and the authentication scheme used.

  • Providers: The Providers interface allows for lookup of provider instances based on a set of search criteria. This interface is expected to be primarily of interest to provider authors wishing to use other providers functionality. It is injectable in both client and server providers.

  • Resource context: The ResourceContext interface provides access to instantiation and initialization of resource or subresource classes in the default per-request scope. It can be injected to help with creation and initialization, or just initialization, of instances created by an application.

  • Configuration: Both the client and the server runtime Configurations are available for injection in providers (client or server) and resource classes (server only).

  • SSE events: SseEventSink represents the incoming SSE connection and provides methods to send events. Sse provides factory methods for events and broadcasters.


This post written by Arjan Tijms suggests that future versions of JAX-RS may have a stronger integration with CDI. So @Context may be deprecated and then removed in favor of @Inject:

JAX-RS 2.2

For some reason, one that has largely been lost in time, JAX-RS uses its own dependency injection system based on @Context instead of CDI's @Inject. While JAX-RS was updated at the last moment before its initial release to have some level of support for CDI, the fact that JAX-RS resources are not CDI beans has unnecessarily hold back the spec and has caused confusion even since JAX-RS was introduced in EE 6 (2009).

This changeover to CDI could possibly happen in 2 steps; in JAX-RS 2.2 everything that can now be injected by @Context should also be injectable using @Inject and JAX-RS resources would be CDI beans by default (perhaps unless explicitly disabled). At the same time @Context would be deprecated. In JAX-RS 3.0 @Context would then be actually removed.

Windsail answered 8/3, 2016 at 13:25 Comment(0)
L
26

The riveting JAX-RS specification defines all the standard types you can inject via @Context.

But if I were you, I would just consult the specific documentation of your chosen provider to see what is available.

For example, RESTEasy provides these values via @Context. Meanwhile, Jersey provides these. Obviously there will be overlap because of the standard context values.

Lati answered 5/1, 2014 at 19:27 Comment(3)
Thanks for the response. For anyone else interested, the correct link for the specification: download.oracle.com/otndocs/jcp/jaxrs-2_0-fr-eval-spec/… (you need to accept the license first)Pahl
The link I provided was correct, but it did have an "AuthParam" after I accepted the license as you say. The edited link without that query parameter should work just fine.Lati
Relevant link to the Jersey user guide. Quote: "These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation."Dripps
E
8

The @Context annotation can be used to inject 12 objects. Here is a quick summary of each of them

  • HttpHeaders - HTTP header valuesand parameters
  • UriInfo - URI query parameters and path variables
  • SecurityContext - Gives access to security-related data for the given HTTP request
  • Request - Allows precondition request processing
  • ServletConfig - The ServletConfig
  • ServletContext - The ServletContext
  • HttpServletRequest - The HttpServletRequest instance for the request
  • HttpServletResponse - The HttpServletResponse instance
  • Application, Configuration, and Providers -> Provide information about the JAX-RS application, configuration and providers
  • ResourceContext - Gives access to resource class instances

All of these instances can be injected in the resource method

@Path("/")
public class EndpointResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
      // Code here that uses httpHeaders
  }
}

or as a field:

@Path("/")
public class EndpointResource {

  private final @Context HttpHeaders httpHeaders;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAllHttpHeaders(){
      // Code here that uses httpHeaders
  }
}

Here is a five part series answering the question What is @Conext used for?

Equatorial answered 21/8, 2017 at 10:22 Comment(1)
When 2 concurrent requests ara handled, Is it guaranteed that httpHeaders field will have different values when called inside getAllHttpHeaders, or are they overwritten by the last request ? In other words, is @Path's behavior similar to @RequestScoped or @ApplicationScoped?Grotesque
K
0

To extend already provided answers: JAX-RS implementations usually provide a way to access the context. For RESTEasy it's ResteasyContext. The context can be listed by

ResteasyContext.getContextDataMap()

Keys of returned map can look like:

interface javax.ws.rs.core.Request
interface javax.ws.rs.core.HttpHeaders
interface javax.ws.rs.ext.Providers
class org.jboss.resteasy.plugins.server.Cleanables
class org.jboss.resteasy.core.PostResourceMethodInvokers
class org.jboss.resteasy.core.InternalDispatcher
interface javax.ws.rs.container.ResourceInfo
interface io.vertx.core.http.HttpServerResponse
interface io.vertx.core.Context
interface org.jboss.resteasy.spi.Registry
interface org.jboss.resteasy.spi.HttpRequest
interface org.jboss.resteasy.spi.ResteasyDeployment
interface javax.ws.rs.container.ResourceContext
interface org.jboss.resteasy.spi.Dispatcher
interface io.vertx.ext.web.RoutingContext
interface io.vertx.core.http.HttpServerRequest
interface io.vertx.core.Vertx
interface javax.ws.rs.core.Configurable
interface org.jboss.resteasy.spi.ResteasyAsynchronousContext
interface javax.ws.rs.core.SecurityContext
interface javax.ws.rs.core.Configuration
interface javax.ws.rs.core.UriInfo
interface org.jboss.resteasy.spi.HttpResponse
Kartis answered 22/5, 2020 at 3:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.