JAX-RS - Injecting Servlet Resources With @Context annotation

[Updated: Dec 10, 2017, Created: Dec 10, 2017]

The @Context annotation can be used to inject a Servlet-managed resources: ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse.

Example

@Path("/")
public class ExampleResource {
  @Context
  private ServletConfig servletConfig;
  @Context
  private ServletContext servletContext;
  @Context
  private HttpServletRequest httpServletRequest;
  @Context
  private HttpServletResponse httpServletResponse;

  @GET
  @Path("/test")
  public void handleRequest() throws IOException {
      System.out.println("-- in resource method --");
      printServletConfigInfo();
      printServletContextInfo();
      printServletRequestInfo();
      //committing response using HttpServletResponse
      httpServletResponse.getWriter().write("Test response");
      httpServletResponse.getWriter().flush();
  }

  private void printServletRequestInfo() {
      System.out.println("-- Servlet Request --");
      System.out.println("Request URI: " + httpServletRequest.getRequestURI());
      Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
      ArrayList<String> list = Collections.list(headerNames);
      System.out.println("Request headers: " + list.size());
      list.forEach(h -> System.out.println(h + " = " + httpServletRequest.getHeader(h)));
  }

  private void printServletContextInfo() {
      System.out.println("-- Servlet Context --");
      System.out.println("Context path: " + servletContext.getContextPath());
      System.out.println("Server info: " + servletContext.getServerInfo());
      Enumeration<String> attributeNames = servletContext.getAttributeNames();
      ArrayList<String> list = Collections.list(attributeNames);
      System.out.println("Context attributes: " + list.size());
      System.out.println("Session Tracking modes: " + servletContext.getDefaultSessionTrackingModes());
  }

  private void printServletConfigInfo() {
      System.out.println("-- Servlet Config Params --");
      Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
      ArrayList<String> list = Collections.list(initParameterNames);
      System.out.println("Init params: " + list.size());
      list.forEach(n -> System.out.println(n + " = " + servletConfig.getInitParameter(n)));
      System.out.println("Servlet name: " + servletConfig.getServletName());
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

The JAX-RS client

public class ExampleClient {
  public static void main(String[] args) {
      Client client = ClientBuilder.newClient();
      WebTarget target =
              client.target("http://localhost:8080/test");
      Response response = target.request()
                                .get();
      System.out.printf("status: %s%n", response.getStatus());
      System.out.printf("-- response body --%n%s%n", response.readEntity(String.class));
  }
}
status: 200
-- response body --
Test response

Output On Server

-- in resource method --
-- Servlet Config Params --
Init params: 0
Servlet name: com.logicbig.example.MyApp
-- Servlet Context --
Context path:
Server info: Apache Tomcat/7.0.47
Context attributes: 9
Session Tracking modes: [COOKIE, URL]
-- Servlet Request --
Request URI: /test
Request headers: 4
user-agent = Jersey/2.25.1 (HttpUrlConnection 1.8.0_65)
host = localhost:8080
accept = text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
connection = keep-alive

Example Project

Dependencies and Technologies Used :

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Injecting Servlet Resources with @Context Example Select All Download
  • access-servlet-resources-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also