Consider this Spring Boot controller method that adds a custom header to the response:
@GetMapping("/greet")
public ResponseEntity greet() {
return ResponseEntity.ok()
.header("X-Custom-Header", "HelloWorld")
.body("Greetings!");
} What will the HTTP response include?
@GetMapping("/greet") public ResponseEntity<String> greet() { return ResponseEntity.ok() .header("X-Custom-Header", "HelloWorld") .body("Greetings!"); }
Think about how ResponseEntity builds the response including headers.
The ResponseEntity builder allows adding headers with the header() method. This code returns status 200 with the body and the custom header included.
You want to add two custom headers X-First and X-Second with values One and Two respectively. Which code snippet does this correctly?
Check the method signatures for adding headers in ResponseEntity.
The header() method adds one header at a time. To add multiple headers, chain multiple header() calls. The headers() method expects an HttpHeaders object, not a Map.
Examine this Spring Boot controller method:
@GetMapping("/test")
public String test(HttpServletResponse response) {
response.setHeader("X-Test", "Value");
return "Hello";
}But the response does not include the X-Test header. Why?
@GetMapping("/test") public String test(HttpServletResponse response) { response.setHeader("X-Test", "Value"); return "Hello"; }
Think about what returning a String means in Spring MVC.
Returning a String without @ResponseBody or ResponseEntity makes Spring treat it as a view name. The response headers set on HttpServletResponse are ignored because the view rendering happens later.
You want to add a header X-App-Version with value 1.0 to every HTTP response from your Spring Boot app. Which approach is correct?
Think about a centralized way to modify all responses.
A Filter can intercept all requests and add headers to the response before passing control. This is the standard way to add headers globally. Adding in every controller is repetitive. @ModelAttribute is for model data, not headers. application.properties does not support custom headers directly.
Given this controller method:
@GetMapping("/multi")
public ResponseEntity multiHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add("X-First", "One");
headers.add("X-Second", "Two");
headers.set("X-First", "Uno");
return new ResponseEntity<>("Done", headers, HttpStatus.OK);
} Which headers will the HTTP response include?
@GetMapping("/multi") public ResponseEntity<String> multiHeaders() { HttpHeaders headers = new HttpHeaders(); headers.add("X-First", "One"); headers.add("X-Second", "Two"); headers.set("X-First", "Uno"); return new ResponseEntity<>("Done", headers, HttpStatus.OK); }
Check the difference between add() and set() methods on HttpHeaders.
The add() method appends a header value, while set() replaces all existing values for that header. So set("X-First", "Uno") replaces the earlier 'One' value.