ZetCode

Spring @RequestHeader

last modified October 18, 2023

In this article we show how to bind method parameters to request headers with @RequestHeader annotation.

Spring is a popular Java application framework for creating enterprise applications.

Spring @RequestHeader

@RequestHeader annotation binds request header values to method parameters. If the method parameter is Map<String, String>, MultiValueMap<String, String>, or HttpHeaders then the map is populated with all header names and values.

Spring @RequestHeader example

The application binds request body headers to method parameters. Requests are created with curl tool.

pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ ├───config
│ │ │ MyWebInitializer.java
│ │ │ WebConfig.java
│ │ └───controller
│ │ MyController.java
│ └───resources
│ logback.xml
└───test
 └───java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.zetcode</groupId>
 <artifactId>springrequestheader</artifactId>
 <version>1.0-SNAPSHOT</version>
 <packaging>war</packaging>
 <properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <maven.compiler.source>17</maven.compiler.source>
 <maven.compiler.target>17</maven.compiler.target>
 <spring-version>5.3.23</spring-version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>ch.qos.logback</groupId>
 <artifactId>logback-classic</artifactId>
 <version>1.4.0</version>
 </dependency>
 <dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>javax.servlet-api</artifactId>
 <version>4.0.1</version>
 <scope>provided</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>${spring-version}</version>
 </dependency>
 </dependencies>
 <build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-war-plugin</artifactId>
 <version>3.3.2</version>
 </plugin>
 <plugin>
 <groupId>org.eclipse.jetty</groupId>
 <artifactId>jetty-maven-plugin</artifactId>
 <version>9.4.49.v20220914</version>
 </plugin>
 </plugins>
 </build>
</project>

We declare the necessary dependencies in pom.xml.

resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <logger name="org.springframework" level="ERROR"/>
 <logger name="com.zetcode" level="INFO"/>
 <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
 <encoder>
 <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
 </Pattern>
 </encoder>
 </appender>
 <root>
 <level value="INFO" />
 <appender-ref ref="consoleAppender" />
 </root>
</configuration>

The logback.xml is a configuration file for the Logback logging library.

com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
@Configuration
public class MyWebInitializer extends
 AbstractAnnotationConfigDispatcherServletInitializer {
 @Override
 protected Class<?>[] getRootConfigClasses() {
 return null;
 }
 @Override
 protected Class<?>[] getServletConfigClasses() {
 return new Class[]{WebConfig.class};
 }
 @Override
 protected String[] getServletMappings() {
 return new String[]{"/"};
 }
}

MyWebInitializer registers the Spring DispatcherServlet, which is a front controller for a Spring web application.

com/zetcode/config/WebConfig.java
package com.zetcode.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.zetcode"})
public class WebConfig implements WebMvcConfigurer {
}

The WebConfig enables Spring MVC annotations with @EnableWebMvc and configures component scanning for the com.zetcode package.

com/zetcode/controller/MyController.java
package com.zetcode.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class MyController {
 private static final Logger logger = LoggerFactory.getLogger(MyController.class);
 @GetMapping(value = "/agent")
 @ResponseStatus(value = HttpStatus.OK)
 public void client(@RequestHeader(value="User-Agent") String userAgent) {
 logger.info("User agent is: {}", userAgent);
 }
 @GetMapping(value = "/all")
 @ResponseStatus(value = HttpStatus.OK)
 public void all(@RequestHeader Map<String, String> headers) {
 logger.info("All headers: {}", headers);
 }
}

We have two mappings. The first mapping determines the user agent, the second mapping finds out all request headers sent.

public void client(@RequestHeader(value="User-Agent") String userAgent) {

With the value parameter of the @RequestHeader, we look for a specific header; in our case, a User-Agent.

public void all(@RequestHeader Map<String, String> headers) {

When providing a map, we retrieve all headers.

$ mvn jetty:run

We start the server.

$ curl localhost:8080/agent

We create a request to the first mapping.

11:33:00.905 INFO com.zetcode.controller.MyController - User agent is: curl/7.81.0 

We get this log.

$ curl localhost:8080/all

We invoke the second mapping.

11:34:59.100 INFO com.zetcode.controller.MyController - All headers: {Accept=*/*, User-Agent=curl/7.81.0, Host=localhost:8080} 

We have three headers logged.

In this article we have used the @RequestHeader annotation to bind request headers to method parameters.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Spring tutorials.

AltStyle によって変換されたページ (->オリジナル) /