Spring @RequestHeader Annotation Example


In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.

Our sample output from this project will look like:

HTTP headers

Spring MVC @RequestHeader Accessing Individual Header Fields

Spring allows us to access individual headers when we use the annotation @RequestHeader and supply a name in one of two ways. We can either specify the annotation @RequestHeader(“Host”) or we can use the value= annotation @RequestHeader(value=”Host”). Remember we will need to supply a String variable with which to assign the header to. The final annotation looks like this: @RequestHeader(“Host”) String hostName.
Sometimes we would like to try to get headers that may not be available. You can either use the required=false setting or use the defaultValue=”XXXX” which will set the required to false implicitly. Doing any of these two will prevent an exception from being thrown in the event that the header is missing in the response.

Note: I have used the required parameter for cache control, @RequestHeader(value=”Cache-Control”, required=false) String cacheControl.

The following code snippet will give you a basic idea.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RestController {
  
  @RequestMapping(value="/showheaders", method=RequestMethod.GET)
  public String getHeaders(@RequestHeader(value="Accept") String acceptType,
                           @RequestHeader(value="Host") String host,
                           @RequestHeader(value="Cache-Control", required=false) String cacheControl,
                           @RequestHeader(value="User-Agent") String userAgent) {
    
    // ....
  }
}

Spring MVC @RequestHeader Accessing All Header Fields

Spring MVC all provides a mechanism where by all the headers can be captured into a Map using the annotation @RequestHeader Map<String,String> headers. You can then iterate through the collection and pull out the individual elements. See the code snippet below.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RestController {

 @RequestMapping(value="/allheaders", method=RequestMethod.GET)
    public String getAllHeaders(Model model, 
                                @RequestHeader Map<String,String> headers ) {
		
    for (String elem: headers.keySet()) {
      logger.info(elem + " : " + headers.get(elem));
    }
    // ....
  }
}

Spring MVC Setting Header Fields

Spring MVC also allows us to set the headers in the response object by using the setHeader() method. The parameters are key/value pairs. Take a look at the highlighted lines

  // ....
 
  @RequestMapping(value="/setheaders", method=RequestMethod.GET)
  @ResponseBody
  public String setHeaders(HttpServletRequest request,HttpServletResponse response) {
    response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader("Expires", 0);

    // ....        
  } 

Complete Spring MVC RESTful Service Controller (RestController.java)

Now we put all the code together for the completed project.

package com.avaldes.tutorial;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RestController {
  
  private static final Logger logger = LoggerFactory.getLogger(RestController.class);
  
  /**
   * Simply chooses a few headers, logs them and add them to model to
   * showHeaders view to render to the user.
   */
  @RequestMapping(value="/showheaders", method=RequestMethod.GET)
  public String getHeaders(Model model,
          @RequestHeader(value="Accept") String acceptType,
          @RequestHeader(value="Accept-Encoding") String acceptEncoding,
          @RequestHeader(value="Accept-Language") String acceptLanguage,
          @RequestHeader(value="Cache-Control", required=false) String cacheControl,
          @RequestHeader(value="Expires", required=false) String expires, 
          @RequestHeader(value="Host") String host,
          @RequestHeader(value="User-Agent") String userAgent) {
    
    logger.info("Inside getHeaders() method...");
    logger.info("Accept : " + acceptType);
    logger.info("Accept-Encoding : " + acceptEncoding);
    logger.info("Accept-Language : " + acceptLanguage);
    logger.info("Cache-Control : " + cacheControl);
    logger.info("Expires : " + expires);
    logger.info("Host : " + host);
    logger.info("User-Agent : " + userAgent);   
    
    model.addAttribute("Accept", acceptType );
    model.addAttribute("AcceptEncoding", acceptEncoding );
    model.addAttribute("AcceptLanguage", acceptLanguage );
    model.addAttribute("CacheControl", cacheControl );
    model.addAttribute("Expires", expires );
    model.addAttribute("Host", host );
    model.addAttribute("UserAgent", userAgent );
    return "showHeaders";
  }
  
  /**
   * getAllHeaders maps ALL RequestHeaders into Map allowing us to 
   * iterate through all elements easily
   */
  @RequestMapping(value="/allheaders", method=RequestMethod.GET)
  public String getAllHeaders(Model model, @RequestHeader Map<String,String> headers ) {
    
    logger.info("Inside getAllHeaders() method...");
    for (String elem: headers.keySet()) {
      logger.info(elem + " : " + headers.get(elem));
      
    }
    // Add entire header Map into model, use JSP to iterate through the collection
    model.addAttribute("headers", headers);
    return "showAllHeaders";
  }
  
  @RequestMapping(value="/setheaders", method=RequestMethod.GET)
  @ResponseBody
  public String setHeaders(HttpServletRequest request,HttpServletResponse response) {
    response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader("Expires", 0);
        
    logger.info("Inside setHeaders() method...");
    logger.info("Cache-Control: no-cache,no-store,must-revalidate");
    logger.info("Pragma: no-cache");
    logger.info("Expires: 0");
        
    return "setHeaders";
  } 
}

Displaying the output in showHeaders View (showHeaders.jsp)

In this JSP view we use JSTL to output each of the individual headers which were inserted into the model as separate attributes via the model.addAttribute() method.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
  <head>
    <title>HTTP Headers</title>
  </head>
<body>
<h1>HTTP Headers</h1>

<pre>
Accept: ${Accept}
Accept-Encoding: ${AcceptEncoding}
Accept-Language: ${AcceptLanguage}
Cache-Control: ${CacheControl}
Expires: ${Expires}
Host: ${Host}
User-Agent: ${UserAgent}
</pre>

</body>
</html>

Displaying the output in showAllHeaders View (showAllHeaders.jsp)

You will notice that this JSP is slightly different than the last in that the headers were not added individually into the model. In this scenario, we added the entire headers collection into the model. We will extract each of the individual elements using the JSTL forEach loop, displaying the key of the header to the left of the colon and the value to the right. The only real difference is that the element keys are all lowercase.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>HTTP Headers</title>
</head>
<body>
<h1>HTTP Headers</h1>

<pre>
<c:forEach var="elem" items="${headers}">
${elem.key} : ${elem.value}</c:forEach>
</pre>

</body>
</html>
HTTP All Headers

Output – After Setting Headers

GET /HeaderExample/setheaders HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: PREF=ID=4f789ee9eae46f:U=ef792e7415ad838e:FF=1:LD=en:TM=090956553:LM=1415310895:GM=1:S=rWeYeFG2Y67J7Eh; 
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20100101 Firefox/17.0
X-Client-Data: CIy2y187209QHWYiptskBCMS2yQEI8IjKARiricoB

HTTP/1.1 200 OK
Cache-Control: no-cache,no-store,must-revalidate
Content-Length: 10
Content-Type: text/html
Date: Sat, 17 Mar 2012 01:39:26 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Pragma: no-cache

Download the Code

That’s It

Hopefully, you will find this helpful to you in understanding how to get the headers individually and via a Map. If you have any questions or comments please let me know.

spring mvc annotations

Related Spring Posts

  • Creating Hello World Application using Spring MVC on Eclipse IDE
    In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program.
  • Spring MVC Form Handling Example
    The following tutorial will guide you on writing a simple web based application which makes use of forms using Spring Web MVC framework. With this web application you will be able to interact with the customer entry form and enter all of the required values and submit them to the backend processes. I have taken the liberty of using CSS to beautify and transform the HTML page from a standard drab look and feel to a more appealing view.
  • Spring @RequestHeader Annotation Example
    In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.
  • Spring MVC Exception Handling using @ExceptionHandler with AngularJS GUI
    Good exception handling is a essential part of any well developed Application Framework and Spring MVC is no exception — pardon the pun. Spring MVC provides several different ways to handle exceptions in our applications. In this tutorial, we will cover Controller Based Exception Handling using the @ExceptionHandler annotation above the method that will handle it.
  • Spring RESTful Web Service Example with JSON and Jackson using Spring Tool Suite
    For this example, I will be using Spring Tool Suite (STS) as it is the best integrated development environment for building the Spring framework projects. Spring is today's leading framework for building Java, Enterprise Edition (Java EE) applications. One additional feature that makes Spring MVC so appealing is that it now also supports REST (REpresentational State Transfer) for build Web Services.
  • Spring MVC RESTful Web Service Example with Spring Data for MongoDB and ExtJS GUI
    This post will show another example of how to build a RESTful web service using Spring MVC 4.0.6, Spring Data for MongoDB 1.6.1 so that we can integrate the web application with a highly efficient datastore (MongoDB 2.6). In this tutorial we will walk you through building the web service and NoSQL database backend and show you how to implement CRUD (Create, Read, Update and Delete) operations.
  • Building DHTMLX Grid Panel User Interface with Spring MVC Rest and MongoDB Backend
    In this tutorial we will show how easy it is to use DHTMLX dhtmlxGrid component while loading JSON data with Ajax pulling in data from the Spring MVC REST web service from our MongoDB data source. You will see how simple it is to create a visually appealing experience for your client(s) with minimal javascript coding.
  • Spring MVC with JNDI Datasource for DB2 on AS/400 using Tomcat
    In this tutorial we will discuss how to set up Spring MVC web services and configure a JNDI Datasource using Tomcat and connect to IBM DB2 Database on a AS/400. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • Java Spring MVC Email Example using Apache Velocity
    In this tutorial we will discuss how to set up a Java Spring MVC RESTful Webservice with Email using Apache Velocity to create a Velocity template that is used to create an HTML email message and embed an image, as shown below, using MIME Multipart Message.
  • Implementing Basic and Advanced Search using Angular Material Design, Grid-UI, Spring MVC REST API and MongoDB Example
    In this tutorial we will discuss how to implement basic and advanced search techniques in MongoDB using AngularJS and Google’s Material Design with Spring MVC REST API backend. The advanced search user interface (UI) will use logical operators and build a JSON object which contains the search field name, boolean or logical operator and the search value.
  • Spring MVC Interceptor using HandlerInterceptorAdapter Example
    In this tutorial we will discuss how to use the HandlerInterceptorAdapter abstract class to create a Spring MVC interceptor. These interceptors are used to apply some type of processing to the requests either before, after or after the complete request has finished executing.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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