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

[sc:spring_mvc ]

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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