JAX-RS @Context Annotation with Examples

1. Overview

The @Context annotation can be used to inject any of the below instances into an instance field or directly into the resource method as a parameter.
The object instances that it can inject are the following:
  • SecurityContext – Security context instance for the current HTTP request
  • Request – Used for setting precondition request processing
  • Application, Configuration, and Providers -> Provide access to the JAX-RS application, configuration, and providers instances
  • ResourceContext – Resource context class instances
  • ServletConfig – The ServletConfig instance instance
  • ServletContext – The ServletContext instance
  • HttpServletRequest – The HttpServletRequest instance for the current request
  • HttpServletResponse – The HttpServletResponse instance for the current request
  • HttpHeaders – Maintains the HTTP header keys and values
  • UriInfo – Query parameters and path variables from the URI called
Let's understand @Context annotation with examples.

2. HTTP headers

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
@Path("testinject")
public class InjectURIDetails{
    //localhost:8080/<root-context>/testinject/httpheaders
    @GET
    @Path("httpheaders")
    public void test(@Context HttpHeaders headers){
        System.out.println("ALL headers -- "+ headers.getRequestHeaders().toString());
        System.out.println("'Accept' header -- "+ headers.getHeaderString("Accept"));
        System.out.println("'TestCookie' value -- "+ headers.getCookies().get("TestCookie").getValue());
    }
}

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
        return Response.ok(httpHeaders.getRequestHeaders()).build();
    }

    @GET
    @Path("/{header-param}")
    @Produces(MediaType.APPLICATION_JSON)
    public  Response getSpecifiedHeader(final @PathParam("header-param") String header_param,
    final @Context HttpHeaders httpHeaders){
        return Response.ok(httpHeaders.getRequestHeader(header_param)).build();
    }

3. 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)
@Path("testinject")
public class InjectURIDetails{
  //localhost:8080/<root-context>/testinject/uriinfo
  @GET
  @Path("uriinfo")
  public void test(@Context UriInfo uriDetails){
      System.out.println("ALL query parameters -- "+ uriDetails.getQueryParameters().toString());
      System.out.println("'id' query parameter -- "+ uriDetails.getQueryParameters.get("id"));
      System.out.println("Complete URI -- "+ uriDetails.getRequestUri());
  }
}

4. HttpServletRequest Details

@Path("/remote-address")
public class HttpServletRequestResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getRemoteAddress(final @Context HttpServletRequest httpServletRequest){
        return Response.ok(httpServletRequest.getRemoteAddr()).build();
    }

}

5. More examples using @Context Annotations

@Path("/resource-context")
public class ResourceContextResource {

    @GET
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(final @Context ResourceContext resourceContext, final @Context UriInfo uriInfo) {
        final CalculatorResource calculatorResource = resourceContext.getResource(CalculatorResource.class);
        int x = Integer.valueOf(uriInfo.getQueryParameters().getFirst("x"));
        int y = Integer.valueOf(uriInfo.getQueryParameters().getFirst("y"));
        return Response.ok(calculatorResource.add(x, y)).build();
    }

}
@Path("/security-context")
public class SecurityContextResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response sayHello(final @Context SecurityContext securityContext) {
        return Response.ok(securityContext.isUserInRole("guest")).build();
    }

}
@Path("servlet-config")
public class ServletConfigResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getServletName(final @Context ServletConfig servletConfig){
        return Response.ok(servletConfig.getServletName()).build();
    }

}
@Path("servlet-context")
public class ServletContextResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getContextPath(final @Context ServletContext servletContext) {
        return Response.ok(servletContext.getContextPath()).build();
    }

}

6. Conclusion

This post explained the important @Context JAX-RS annotation.
Learn more about Jersey Rest framework on Jersey Rest Developer Guide.
All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.


Comments