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 (javax.ws.rs.HeaderParam)
  • @Context(javax.ws.rs.core.Context)
  • @Path (javax.ws.rs.Path)
  • @GET (javax.ws.rs.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

IBookService.java

package com.jersey.series.headerparam;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

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

BookServiceImpl.java

package com.jersey.series.headerparam;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

@Path("bookservice")
public class BookServiceImpl implements IBookService {

	// http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getheader
	@GET
	@Path("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
	@GET
	@Path("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 !!

 

Testing

 

1. Using Google chrome web browser client

 

Enter URL for the 1st service
http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getheader
1_Jersey-HeaderParam_first_service

Enter URL for the 2nd service
http://localhost:8080/Jersey-HeaderParam/rest/bookservice/getallheader
2_Jersey-HeaderParam_second_service

 

2. Java client

Uses Client, ClientBuilder, WebTarget and Response classes from core JAX-RS package javax.ws.rs.client for invoking Restful web service

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

TestHeaderParam.java

package test.jersey.series.headerparam;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientConfig;

public class TestHeaderParam {

	public static void main(String[] args) {

		// setting & invoking first request
		System.out.println("Using @HeaderParam");
		System.out.println("---------------------");
		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");
		System.out.println("---------------------");
		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;

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

			// 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) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
			client.close();
		}
		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