Video in progress

Junior 🌱 Spring

How do you read HTTP header and cookie values in a controller?

You read a header with @RequestHeader and a cookie with @CookieValue. Both are required by default; to make them optional, set required = false or a defaultValue.

📖 Answer

@GetMapping("/profile")
ProfileDto profile(
        @RequestHeader("Accept-Language") String lang,
        @RequestHeader(value = "X-Request-Id", required = false) String requestId,
        @CookieValue(value = "theme", defaultValue = "light") String theme) {
    return service.load(lang, theme);
}

If you need all the headers, take @RequestHeader HttpHeaders headers or @RequestHeader Map<String, String> all.

Good to know:

  • if a required header is missing, Spring returns 400 Bad Request and your method isn't even called;
  • header names are case-insensitive;
  • don't read the Authorization header by hand in a controller and verify the token yourself. That's Spring Security's job;
  • to set a cookie, build a ResponseCookie and add it to the ResponseEntity as a Set-Cookie header.