In this article we will try to understand how we can access header information inside controller using spring framework. Spring provide way using that we can  access single header information or all header information at time.

@RequestHeader is annotation using that we can access header information which are passed in request object by client.

Project Structure :

spring-java-configuration-headers

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>spring-java-configuration-headers</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring-java-configuration-headers</name>
    <properties>
        <spring.version>4.3.1.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring-hello-work</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

HelloController.java

package com.springdemo.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/")
public class HelloController {

    // When an @RequestHeader annotation is used on a Map<String, String>, MultiValueMap<String, String>, or HttpHeaders argument, the map is populated with all header values.
    @RequestMapping("getAllHeaders")
    public String getAllHeaders(@RequestHeader Map<String, String> headers, ModelMap model) {
        Map<String, String> headersInfo = new HashMap<>();
        headers.forEach((headerName, headerValue) -> {
            headersInfo.put(headerName, headerValue);
            System.out.println(headerName + "->" + headerValue);
        });
        model.put("headers", headersInfo);
        return "allHeaders";
    }
    // When an @RequestHeader annotation is used on a Map<String, String>, MultiValueMap<String, String>, or HttpHeaders argument, the map is populated with all header values.
    @RequestMapping("getAllMultiHeaders")
    public String getAllHttpHeaders(@RequestHeader HttpHeaders httpHeaders, ModelMap model) {
        Map<String, List> headersInfo = new HashMap<>();
        httpHeaders.forEach((headerName, headerValue) -> {
            headersInfo.put(headerName, headerValue);
            System.out.println(headerName + "->" + headerValue);
        });
        model.put("headers", headersInfo);
        return "allHeaders";
    }
    // When an @RequestHeader annotation is used on a Map<String, String>, MultiValueMap<String, String>, or HttpHeaders argument, the map is populated with all header values.
    @RequestMapping("getHeader")
    public String getHeader(@RequestHeader("accept-encoding") String acceptEncoding, @RequestHeader("Accept") String accept, @RequestHeader(value = "Keep-Alive", defaultValue = "none") String keepAlive, ModelMap model) {
        Map<String, String> headersInfo = new HashMap<>();
        headersInfo.put("accept-encoding", acceptEncoding);
        headersInfo.put("Accept", accept);
        headersInfo.put("Keep-Alive", keepAlive);
        model.put("headers", headersInfo);
        return "allHeaders";
    }

    // When an @RequestHeader annotation is used on a Map<String, String>, MultiValueMap<String, String>, or HttpHeaders argument, the map is populated with all header values.
    @RequestMapping("getCookies")
    public String getSessionCookies(@CookieValue("JSESSIONID") String sessionId, ModelMap model) {
        Map<String, String> headersInfo = new HashMap<>();
        headersInfo.put("JSESSIONID", sessionId);
        model.put("headers", headersInfo);
        return "allHeaders";
    }
}

allHeaders.jsp

<%@ taglib prefix="c"
           uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<table>
    <tr>
        <th>
            Header Name
        </th>
        <th>
            Header Value
        </th>
    </tr>
<c:forEach var="type" items="${headers}">
    <tr>
            <td>
                    ${type.key}
            </td>
            <td>
                    ${type.value}
            </td>
        </tr>

</c:forEach>
</table>
</body>
</html>

SpringWebConfig.java

package com.springdemo.configs;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 * Created by Lenovo on 19-01-2017.
 */
@Configuration
@ComponentScan({ "com.springdemo" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver  viewResolver () {
        InternalResourceViewResolver  viewResolver=new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

WebConfigs.java

package com.springdemo.configs;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 * Created by Lenovo on 19-01-2017.
 */
public class WebConfigs extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { SpringWebConfig.class };
    }
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

Download source code

spring-java-configuration-headers

Was this post helpful?

Leave a Reply

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