Video in progress
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 Requestand your method isn't even called; - header names are case-insensitive;
- don't read the
Authorizationheader by hand in a controller and verify the token yourself. That's Spring Security's job; - to set a cookie, build a
ResponseCookieand add it to theResponseEntityas aSet-Cookieheader.
Sign up to mark studied questions and save your progress.