RESTful Web Services @HeaderParam Example using JAX-RS and Jersey

@HeaderParam Example

In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract header fields transmitted as part of the HTTP request and response objects in HTTP using @HeaderParam annotation. Header fields are colon-separated name-value pairs in clear-text string format, terminated by a carriage return (CR) and line feed (LF) character sequence. The end of the header section is indicated by an empty field, resulting in the transmission of two consecutive CR-LF pairs. This can be easily seen by examining the HTTP request using an addon like Live HTTP Headers available on Google Chrome.

GET /RestfulHeaderExample/rest/headers HTTP/1.1
Host: localhost:8080
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36


HTTP/1.1 200 OK
Content-Type: text/html
Date: Thu, 24 Oct 2013 00:05:25 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked

This RESTful web service will have only one endpoint. This endpoint’s sole purpose is to capture a few of the header parameters available to us in the HTTP request object and display them back to the user by creating a response object and appending all the parameters.

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Jersey JAX-RS
  • log4J (for logging purposes)

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

asm-3.1.jar
jersey-client-1.18.jar
jersey-core-1.18.jar
jersey-json-1.18.jar
jersey-server-1.18.jar
jersey-servlet-1.18.jar
jsr311-api-1.1.1.jar
log4j-1.2.17.jar

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

jax-rs headerparam proj

RESTful Web Service End Points

#URIMethodDescription
1/rest/headersGETUsed to test out the web service and extract header information from the HTTP request object

Using the @HeaderParam in JAX-RS API

http://localhost:8080/RestfulHeaderExample/rest/headers

Complete Program using @HeaderParam

package com.avaldes;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

@Path("/headers")
public class RestfulHeaderExample {
  static Logger logger = Logger.getLogger(RestfulHeaderExample.class);
  
  @GET
  @Produces(MediaType.TEXT_HTML)
  public Response showHeaders(@HeaderParam("Accept") String accept, 
                @HeaderParam("Host") String host,
                @HeaderParam("Cache-Control") String cache,
                @HeaderParam("User-Agent") String useragent,
                @HeaderParam("Referer") String referer) {

    StringBuffer msg = new StringBuffer("Inside showHeaders: <br/><br/>");
    msg.append("Accept : ");
    msg.append(accept);
    msg.append("<br/>");
    msg.append("Host : ");
    msg.append(host);
    msg.append("<br/>");
    msg.append("Cache-Control : ");
    msg.append(cache);
    msg.append("<br/>");
    msg.append("User-Agent : ");
    msg.append(useragent);
    msg.append("<br/>");
    msg.append("Referer : ");
    msg.append(referer);
    msg.append("<br/>");
    logger.info(msg);
    
    return Response.ok(msg.toString()).entity(msg.toString()).build();
  }
}

Web Deployment Descriptor (web.xml)

This is a pretty straight forward deployment descriptor file – only thing you need to add is the location of you java package in the Jersey ServletContainer entry as init-param. Please ensure you add it to the web.xml file as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.omega.rest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
 
   <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.avaldes</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Testing out the Web Services

In this example our web service will be using the @HeaderParam parameters to extract header fields from the Request object and inject the values into our Java variables. We will use these values and construct a response object with each of the headers clearly labeled and display the results back to the user.

headerparam test1

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java jaxrs headerparam

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply to pick n pull ri Cancel reply

Your email address will not be published. Required fields are marked *