RestEasy: JAX-RS 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

JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc

@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 7.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; RestEasy-HeaderParam. Initial path for this application is http://localhost:8080/RestEasy-HeaderParam

We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/customer” using @Path annotation. Next respective path for each method annotated with @Path (method-level)

Customer Service interface

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: It’s always a good programming practice to do code-to-interface and have its implementation separately

ICustomerService.java

package com.resteasy.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("/customer")
public interface ICustomerService {

	// http://localhost:8080/RestEasy-HeaderParam/resteasy/customer/getheader - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-HeaderParam/resteasy/customer/getheader - JBoss AS7
	@GET
	@Path("getheader")
	public Response getHeaderDetails(
			@HeaderParam("User-Agent") String userAgent,
			@HeaderParam("Content-Type") String contentType,
			@HeaderParam("Accept") String accept
			);

	// http://localhost:8080/RestEasy-HeaderParam/resteasy/customer/getallheader - Tomcat 7.0.x
	// http://localhost:9090/RestEasy-HeaderParam/resteasy/customer/getallheader - JBoss AS7
	@GET
	@Path("getallheader")
	public Response getAllHeader(@Context HttpHeaders httpHeaders);
}

Customer Service implementation

Implements above interface returning Response object for both methods

CustomerServiceImpl.java

package com.resteasy.series.headerparam;

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

public class CustomerServiceImpl implements ICustomerService {

	public Response getHeaderDetails(String userAgent, String contentType, String accept) {

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

	public Response getAllHeader(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();
	}
}

 

Deployment

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

Test the service !!

Testing

 

1.  Using Google chrome web browser client

 

Enter URL for the 1st service:
http://localhost:8080/RestEasy-HeaderParam/resteasy/customer/getheader

1_RestEasy-HeaderParam_first_service

 

Enter URL for the 2nd service:
http://localhost:8080/RestEasy-HeaderParam/resteasy/customer/getallheader

2_RestEasy-HeaderParam_second_service

 

2. Java client (RestEasy)

There are two test clients which comes from JBoss RestEasy package org.jboss.resteasy.client and org.jboss.resteasy.client.jaxrs

  1. using ClientRequest and ClientResponse classes for first service
  2. using ResteasyClient, ResteasyClientBuilder and ResteasyWebTarget classes for second service

TestHeaderParam.java

package test.resteasy.series.headerparam;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class TestHeaderParam {

	public static void main(String[] args) throws Exception {

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

		// setting & invoking second request
		System.out.println("\n\nUsing @Context");
		System.out.println("---------------------");
		String url2 = "http://localhost:8080/RestEasy-HeaderParam/resteasy/customer/getallheader";
		String responseString3 = testGetAllHeader(url2);
		System.out.println("Response String for Second Service : \n" + responseString3);
	}

	/**
	 * using ClientRequest and ClientResponse classes from  org.jboss.resteasy.client
	 * @param url
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String testGetHeader(String url) throws Exception {

		// local variables
		ClientRequest clientRequest = null;
		ClientResponse<String> clientResponse = null;
		int responseCode;
		String responseString = null;

		try{
			clientRequest = new ClientRequest(url);
			clientRequest.setHttpMethod(HttpMethod.GET);
			clientRequest.accept(MediaType.APPLICATION_FORM_URLENCODED);
			clientResponse = clientRequest.get(String.class);

			responseCode = clientResponse.getResponseStatus().getStatusCode();
			System.out.println("Response code: " + responseCode);

			if(clientResponse.getResponseStatus().getStatusCode() != 200) {
				throw new RuntimeException("Failed with HTTP error code : " + responseCode);
			}

			System.out.println("ResponseMessageFromServer: " + clientResponse.getResponseStatus().getReasonPhrase());
			responseString = clientResponse.getEntity();
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			clientResponse.close();
			clientRequest.clear();
		}
		return responseString;
	}

	/**
	 * using ResteasyClient, ResteasyWebTarget and Response classes from org.jboss.resteasy.client
	 * @param url
	 */
	public static String testGetAllHeader(String url) {

		// local variables
		ResteasyClient resteasyClient = null;
		ResteasyWebTarget resteasyWebTarget = null;
		Response response = null;
		int responseCode;
		String responseString = null;

		try{
			resteasyClient = new ResteasyClientBuilder().build();
			resteasyWebTarget = resteasyClient.target(url);
			response = resteasyWebTarget.request().get();

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

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

			System.out.println("ResponseMessageFromServer: " + response.getStatusInfo().getReasonPhrase());
			responseString = response.readEntity(String.class);

		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		finally{
			// release resources, if any
			response.close();
		}
		return responseString;
	}
}

Output in console

Using @HeaderParam
---------------------
Response code: 200
ResponseMessageFromServer: OK
Response String for First Service : 
User-Agent: Apache-HttpClient/4.2.1 (java 1.5)
Content-Type: null
Accept: application/x-www-form-urlencoded


Using @Context
---------------------
Response code: 200
ResponseMessageFromServer: OK
Response String for Second Service : 
accept-encoding: gzip, deflate
connection: Keep-Alive
host: localhost:8080

Download project (Tomcat Server 7.0.x)

RestEasy-@HeaderParam-annotation (Tomcat server) (9kB)

 

JBoss Deployment

  1. Update pom.xml with resteasy scope “provided” for dependencies as JBoss AS7 modules already contains these dependent jars
    <resteasy.scope>provided</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
    
  2. Update web.xml
    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
    	<display-name>RestEasy-HeaderParam</display-name>
    
    	<!-- RestEasy Servlet -->
    	<servlet-mapping>
    		<servlet-name>javax.ws.rs.core.Application</servlet-name>
    		<url-pattern>/resteasy/*</url-pattern>
    	</servlet-mapping>
    
    	<!-- welcome file -->
    	<welcome-file-list>
    		<welcome-file>index.html</welcome-file>
    	</welcome-file-list>
    
    </web-app>
    
    
  3. Rest remain the same
  4. Read through this article which explains development & deployment of RestEasy web service with JBoss Application Server in detail

Note: JBoss Application Server 7.1.1.Final comes with default RestEasy distribution with version 2.3.2.Final. So update JBoss AS7 with latest RestEasy version. Look at this article, which explains how to update default version with latest version available in the JBoss community

Download project (JBoss Application Server 7.1.1.Final)

RestEasy-@HeaderParam-annotation (JBoss server) (9kB)

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

Happy Coding !!
Happy Learning !!

RestEasy: JAX-RS web service using JAXB + XML example
RestEasy: JAX-RS web service using @FormParam annotation