Jersey 2.x web service using @HeaderParam/@Context annotations

In this article, we will learn and implement an example to get header details of Restful web service using @HeaderParam and @Context annotations

Jersey is the most popular amongst Restful web service development. Latest Jersey 2.x version has been developed by Oracle/Glassfish team in accordance with JAX-RS 2.0 specification. Earlier Jersey 1.x version was developed and supported by Oracle/Sun team

Latest Jersey release version is 2.12 see here and look documentation and API for details. We will implement Jersey examples in the following articles based on latest 2.x version

@HeaderParam binds HTTP header to formal arguments of Java method

Using @Context annotation in the program, you can get all possible headers passed in the request like

  • Content-Type
  • Accept
  • User-Agent
  • Connection
  • Host
  • etc

Annotation Used

  • @HeaderParam (
  • @Context(
  • @Path (
  • @GET (

Files like

  • pom.xml,
  • web.xml

Remain the same with little modification in the package name used for the project from the previous one. Take a look at one of the following articles to understand these files and their description in detail

  • @PathParam
  • @QueryParam
  • @MatrixParam
  • @FormParam

Now, we move on to the implementation to retrieve HTTP headers from the requesting client

Let’s see coding in action


URL Pattern

Http url for any common web application is http://<server>:<port>/<root-context>/<from_here_application_specific_path>

In our example, we are going to deploy the war into Tomcat 8.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; Jersey-HeaderParam. Initial path for this application is http://localhost:8080/Jersey-HeaderParam

We have configured “/rest/*” as url-pattern for the “jersey-servlet” servlet in web.xml and at class-level path configured is “/bookservice” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Book Service interface

Defines two abstract methods for retrieving headers sent along with HTTP request

NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately

package com.jersey.series.headerparam;


public interface IBookService {

	public Response getHeaderDetails(String userAgent, String contentType, String accept);
	public Response getAllHeader(HttpHeaders httpHeaders);

Book Service implementation

Implements above interface returning Response object for both methods

Defines two simple methods to retrieve HTTP header details from the requesting client

  • First method takes three-arguments which are mapped to the formal arguments using @HeaderParam annotation
  • Second method retrieves all possible header sent in the requesting client and their values using HttpHeaders which are mapped using @Context annotation

Note: Jersey doesn’t inherit JAX-RS annotations. So we are annotating Resource/Provider classes and then defining qualified package name in web.xml

package com.jersey.series.headerparam;


public class BookServiceImpl implements IBookService {

	// http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getheader
	public Response getHeaderDetails(
			@HeaderParam("User-Agent") String userAgent,
			@HeaderParam("Content-Type") String contentType,
			@HeaderParam("Accept") String accept

		String header = "User-Agent: " + userAgent +
				"\nContent-Type: " + contentType +
				"\nAccept: " + accept;
		return Response.status(200).entity(header).build();

	// http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getallheader
	public Response getAllHeader(@Context HttpHeaders httpHeaders){

		// local variables
		StringBuffer stringBuffer = new StringBuffer();
		String headerValue = "";

		for(String header : httpHeaders.getRequestHeaders().keySet()) {
			headerValue = httpHeaders.getRequestHeader(header).get(0);
			stringBuffer.append(header + ": " + headerValue + "\n");
		return Response.status(200).entity(stringBuffer.toString()).build();


Tomcat-8.0.12 Deployment

  • Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
  • Copy(ctrl+c) the war file from the target folder
  • Paste(ctrl+v) it into apache tomcat (webapps folder)
  • Start the tomcat server


Glassfish-4.1 Deployment

  • Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
  • Once you see “BUILD SUCCESS” after running maven command, keep the war file ready to be deployed
  • There are two ways to deploy war file into Glassfish-4.1
    1. Online
    2. Offline
  • Click here to understand above deployments process in detail

Test the service !!




1. Using Google chrome web browser client


Enter URL for the 1st service

Enter URL for the 2nd service


2. Java client

Uses Client, ClientBuilder, WebTarget and Response classes from core JAX-RS package for invoking Restful web service

Note: Commented lines will help out us to try (set) various request header parameters

package test.jersey.series.headerparam;


import org.glassfish.jersey.client.ClientConfig;

public class TestHeaderParam {

	public static void main(String[] args) {

		// setting & invoking first request
		System.out.println("Using @HeaderParam");
		String url = "http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getheader";
		String responseString1 = testGetHeaders(url);
		System.out.println("Response String for First Service : \n\n" + responseString1);

		// setting & invoking second request
		System.out.println("\n\nUsing @Context");
		String url2 = "http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getallheader";
		String responseString2 = testGetHeaders(url2);
		System.out.println("Response String for Second Service : \n\n" + responseString2);

	public static String testGetHeaders(String httpURL) {

		// local variables
		ClientConfig clientConfig = null;
		Client client = null;
		WebTarget webTarget = null;
		Builder builder = null;
		Response response = null;
		int responseCode;
		String responseMessageFromServer = null;
		String responseString = null;

			// invoke service after setting necessary parameters
			clientConfig = new ClientConfig();
			client =  ClientBuilder.newClient(clientConfig);
			//"Content-Type", MediaType.TEXT_PLAIN);
			//"accept", MediaType.TEXT_PLAIN);
			webTarget =;

			// invoke service
			builder = webTarget.request(MediaType.TEXT_PLAIN).accept(MediaType.TEXT_PLAIN);
			response = builder.get();

			// get response code
			responseCode = response.getStatus();
			System.out.println("Response code: " + responseCode);

			if (response.getStatus() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);

			// get response message
			responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
			System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

			// get response string
			responseString = response.readEntity(String.class);
		catch(Exception ex) {
			// release resources, if any
		return responseString;

Output in console

Using @HeaderParam
Response code: 200
ResponseMessageFromServer: OK
Response String for First Service : 

User-Agent: Jersey/2.12 (HttpUrlConnection 1.7.0_06-ea)
Content-Type: null
Accept: text/plain,text/plain

Using @Context
Response code: 200
ResponseMessageFromServer: OK
Response String for Second Service : 

accept: text/plain,text/plain
user-agent: Jersey/2.12 (HttpUrlConnection 1.7.0_06-ea)
host: localhost:8080
connection: keep-alive

Conclusion:  When it is required to get HTTP header details along with requesting parameters either via query/path then @HeaderParam or @Context will be quite useful

Download project

Jersey-2x-HeaderParam (8kB)

Happy Coding !!
Happy Learning !!

Jersey 2.x web service using JAXB + XML example
Jersey 2.x web service using @FormParam annotation