Quick revision
The short answer
We read the header with @RequestHeader("X-Request-Id") String requestId and the cookie with @CookieValue(name = "session_hint", required = false) String hint. We build the response cookie with ResponseCookie.from(name, value).httpOnly(true).secure(true).sameSite("Lax").path("/").build() and send it with ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()). A required header or cookie that is missing makes Spring answer 400 Bad Request.
What to remember
In this answer, we read a header with @RequestHeader and an optional cookie with @CookieValue(required = false), built a secure cookie with ResponseCookie and its HttpOnly, Secure, SameSite, Path and Max-Age attributes, and sent it through ResponseEntity with the Set-Cookie header. We also saw that a missing required header or cookie ends in 400 before our method runs, and how required = false, defaultValue or Optional change that.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We read the header with @RequestHeader("X-Request-Id") String requestId and the cookie with @CookieValue(name = "session_hint", required = false) String hint. We build the response cookie with ResponseCookie.from(name, value).httpOnly(true).secure(true).sameSite("Lax").path("/").build() and send it with ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()). A required header or cookie that is missing makes Spring answer 400 Bad Request.
Background to this question
Headers and cookies carry a lot of the context of a request: a request id for tracing, a hint about the user's session, a preference set in an earlier visit. Reading them is easy in Spring MVC, but writing a cookie safely takes a few attributes that are easy to forget, and the wrong default can leak a cookie to scripts or over plain HTTP. In this answer, we will recap what headers and cookies are, write the controller method, look closely at each cookie attribute, and see what Spring does when a required value is missing.
1A Quick Recap of Headers and Cookies
An HTTP header is a name and value sent with a request or response, such as X-Request-Id: 7f3a. Names are case-insensitive, so x-request-id is the same header. A cookie is a small value that the server asks the browser to store with a Set-Cookie response header; the browser then sends it back on later requests in a single Cookie header, such as Cookie: session_hint=dark; lang=en.
On the server, Spring MVC can bind both directly to method parameters. @RequestHeader binds a header, and @CookieValue binds one cookie by name from the Cookie header. Both are required by default, which matters for the last section.
2Writing the Controller Method
Here is a complete method that reads both values and sets a new secure cookie in the response.
6 messages in order. Play them, or step through them one at a time.
Notice that the header parameter has no required = false, so the request id is mandatory, while the cookie is optional and arrives as null when the browser has not stored it yet. ResponseCookie is Spring's immutable builder for a Set-Cookie value; its toString() produces exactly the header text, which we add with ResponseEntity's header method. We could also add the header to an HttpServletResponse parameter, but returning everything through ResponseEntity keeps the method easy to test.
3What Each Cookie Attribute Protects Against
Each attribute closes a specific hole. HttpOnly tells the browser not to expose the cookie to JavaScript through document.cookie, so a cross-site scripting bug cannot read it. Secure means the browser only sends the cookie over HTTPS, so it never travels in plain text. SameSite=Lax means the browser does not send the cookie on requests that other sites start in the background, such as a form posted from another site, but does send it when the user follows a normal link; this blocks most cross-site request forgery. SameSite=Strict is tighter, and SameSite=None allows cross-site use but then requires Secure.
Path=/ makes the cookie apply to every path of the site; without it, the browser uses the path of the request that set it, which leads to cookies that seem to vanish on other pages. Max-Age sets how long the browser keeps it, in seconds; without it, the cookie is a session cookie and disappears when the browser closes. We can also delete a cookie by sending the same name and path with maxAge(0).
The name and path must match the original cookie, or the browser treats it as a different cookie and keeps the old one.
4What Happens When a Value Is Missing
If the client forgets the X-Request-Id header, Spring cannot bind a required parameter. It throws MissingRequestHeaderException, which the default exception handling maps to 400 Bad Request. A required cookie that is missing throws MissingRequestCookieException, also 400. The method itself never runs.
So the choice of required is part of the API contract. A request id is often better generated by a filter when it is missing, so every request has one, while a hint cookie should almost always be optional because first-time visitors never have it. We can also use Optional<String> as the parameter type, which Spring treats as not required.
5Follow-up questions
How do we read all headers at once?
We can declare @RequestHeader Map<String, String> headers, or better @RequestHeader HttpHeaders headers, which handles case-insensitive names and multiple values. That is useful for logging or forwarding, but for values the method actually depends on, a named parameter documents the contract more clearly.
Why use ResponseCookie instead of jakarta.servlet.http.Cookie?
The servlet Cookie class historically had no SameSite attribute, so people built header strings by hand. ResponseCookie supports every modern attribute, is immutable, and works in both Spring MVC and WebFlux, so the same code builds cookies in either stack.
Should a security token be stored in a cookie like this?
If the cookie holds a session id or token, the attributes we used, HttpOnly, Secure and SameSite, are the minimum, and the value must be random and long. Usually the session cookie is managed by Spring Session or the container, and a hint cookie like ours should hold only non-sensitive data.
6Conclusion
In this answer, we read a header with @RequestHeader and an optional cookie with @CookieValue(required = false), built a secure cookie with ResponseCookie and its HttpOnly, Secure, SameSite, Path and Max-Age attributes, and sent it through ResponseEntity with the Set-Cookie header. We also saw that a missing required header or cookie ends in 400 before our method runs, and how required = false, defaultValue or Optional change that.
Open with
In the controller method I would declare the header as @RequestHeader("X-Request-Id") String requestId and the cookie as @CookieValue(name = "session_hint", required = false) String hint, because a first-time visitor will not have the cookie yet and I do not want that to fail.
Then, if they want more
Both annotations are required by default, so if a required header or cookie is missing, Spring throws MissingRequestHeaderException or MissingRequestCookieException and answers 400 before the method runs.
To set the cookie I would use Spring's ResponseCookie builder: ResponseCookie.from("session_hint", value), then httpOnly(true) so JavaScript cannot read it, secure(true) so it only travels over HTTPS, sameSite("Lax") to block most cross-site request forgery, path("/") so it applies to the whole site, and usually a maxAge. Then I return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()).body(result).
Returning everything through ResponseEntity keeps the method easy to test with MockMvc. To delete the cookie later I would send the same name and path with maxAge zero.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Read a header X-Request-Id and a cookie session_hint in a controller method, and set a...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/6003fdc139/