What if you could add important info to every server response with just one simple change?
Why Custom response headers in Spring Boot? - Purpose & Use Cases
Imagine you want to add extra information to every response from your web server, like telling the browser about caching rules or security policies, but you have to add these details manually to each response.
Manually adding headers to every response is tedious, easy to forget, and can lead to inconsistent behavior across your app. It also clutters your code and makes maintenance harder.
Custom response headers let you define extra information once and have it automatically included in all or specific responses, keeping your code clean and consistent.
response.setHeader("X-Custom-Info", "value"); // in every controller method
@RestControllerAdvice public class HeaderAdvice { @ModelAttribute public void addHeaders(HttpServletResponse response) { response.setHeader("X-Custom-Info", "value"); } }
This makes it easy to control response behavior globally, improving security, caching, and client communication without repeating code.
For example, adding a security header like X-Content-Type-Options: nosniff to every response helps protect users from certain attacks without changing each controller.
Manually adding headers is repetitive and error-prone.
Custom response headers automate and centralize this task.
This leads to cleaner code and better app behavior.
Practice
Solution
Step 1: Understand what response headers do
Response headers carry metadata or extra info about the response from server to client.Step 2: Identify the purpose of custom headers
Custom headers add extra info beyond standard headers, helping clients handle responses better.Final Answer:
To send extra information from the server to the client along with the response -> Option AQuick Check:
Custom headers = extra info sent [OK]
- Confusing headers with request body changes
- Thinking headers change HTTP methods
- Assuming headers encrypt data automatically
X-Custom-Header with value 12345 using ResponseEntity in Spring Boot?Solution
Step 1: Recall ResponseEntity builder pattern
ResponseEntity.ok() starts building a 200 OK response, then header() adds headers, then body() sets the body.Step 2: Check method chaining order
Correct chaining is ResponseEntity.ok().header(...).body(...). Other orders or methods like setHeader() do not exist or cause errors.Final Answer:
return ResponseEntity.ok().header("X-Custom-Header", "12345").body(data); -> Option CQuick Check:
Use ok() then header() then body() [OK]
- Calling header() after body()
- Using non-existent setHeader() method
- Wrong method chaining order
public ResponseEntity<String> getData() {
return ResponseEntity.ok()
.header("X-Rate-Limit", "1000")
.header("X-Request-ID", "abc123")
.body("Success");
}What headers will the client receive in the response?
Solution
Step 1: Analyze header() calls in method
Two header() calls add "X-Rate-Limit" with "1000" and "X-Request-ID" with "abc123".Step 2: Confirm both headers are included in response
ResponseEntity accumulates headers, so both custom headers are sent with the response.Final Answer:
X-Rate-Limit: 1000 and X-Request-ID: abc123 -> Option DQuick Check:
Multiple header() calls add multiple headers [OK]
- Assuming only last header() call applies
- Thinking headers overwrite each other
- Ignoring headers and focusing on body only
@GetMapping("/test")
public ResponseEntity<String> test() {
ResponseEntity<String> response = ResponseEntity.ok();
response.header("X-Test", "value");
return response.body("Done");
}Solution
Step 1: Understand ResponseEntity immutability
ResponseEntity.ok() returns a builder, but here it's assigned to ResponseEntity, which is immutable.Step 2: header() returns a new builder; original is unchanged
Calling header() on ResponseEntity does nothing; must chain calls on builder before building.Final Answer:
ResponseEntity.ok() returns an immutable object; header() does not modify it in place -> Option BQuick Check:
ResponseEntity is immutable; use builder chaining [OK]
- Trying to modify ResponseEntity after creation
- Confusing builder with built object
- Missing chaining of header() before body()
X-User-Status with value active only if a user is logged in, otherwise no header. Which is the best way to implement this in a Spring Boot controller method?Solution
Step 1: Understand conditional header addition
ResponseEntity builder allows conditional chaining of header() before body() to add headers only when needed.Step 2: Avoid adding headers after body() or always adding unconditionally
Adding header after body() is invalid; always adding ignores condition; modifying HttpServletResponse is less clean.Final Answer:
Use ResponseEntity builder and conditionally call header() before body() based on login status -> Option AQuick Check:
Conditionally chain header() before body() [OK]
- Adding headers after body() call
- Ignoring login condition and always adding header
- Directly modifying HttpServletResponse instead of ResponseEntity
Ready to prove it?
Pass the test and this pattern moves unknown
