Reading Headers
A request header is a small named fact that travels with a request. Headers travel with every request, unseen in the address.
Read one header
Send GET /who with the X-Name header set to Ana. The method greets that name.
@GetMapping("/who")
public String who(@RequestHeader(value = "X-Name", defaultValue = "Guest") String name) {
return "Hello, " + name + "!";
}Read the sender
The User-Agent header names the program that sent the request. This method echoes it back.
@GetMapping("/agent")
public String agent(@RequestHeader("User-Agent") String agent) {
return agent;
}Example
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WhoController {
@GetMapping("/who")
public String who(@RequestHeader(value = "X-Name", defaultValue = "Guest") String name) {
return "Hello, " + name + "!";
}
}Key points
- Headers travel with every request.
- @RequestHeader reads one header by name.
- The value arrives as a method argument.
- A missing header gives an error answer by default.
- defaultValue gives a value when the header is missing.
- The User-Agent header names the program that sent the request.
- Header names are not case sensitive.
In this example, the controller has one route. The route answers GET requests for /who. The method reads the X-Name header into name. The default is Guest when the header is missing. The method joins the name into a greeting. The first request carries the header with Ana and gets Hello, Ana! back. The second request carries no header and gets Hello, Guest! back.
Note
A header is not part of the address, so it never shows in the browser bar.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @RequestHeader(value = "X-Name", defaultValue = "Guest") do?