Spring Boot - REST ControllersYou want to return a JSON response with status 202 Accepted, a custom header "X-Request-ID" set to "abc123", and a body containing a Map with key "message" and value "Processing". Which code snippet correctly achieves this?Areturn ResponseEntity.status(HttpStatus.ACCEPTED) .header("X-Request-ID", "abc123") .body(Map.of("message", "Processing"));Breturn ResponseEntity.body(Map.of("message", "Processing")) .header("X-Request-ID", "abc123") .status(HttpStatus.ACCEPTED);Creturn new ResponseEntity<>(Map.of("message", "Processing"), HttpStatus.ACCEPTED, Map.of("X-Request-ID", "abc123"));Dreturn ResponseEntity.create(HttpStatus.ACCEPTED, Map.of("message", "Processing")) .header("X-Request-ID", "abc123");Check Answer
Step-by-Step SolutionSolution:Step 1: Use correct builder patternResponseEntity builder requires calling status() first, then header(), then body().Step 2: Validate optionsreturn ResponseEntity.status(HttpStatus.ACCEPTED) .header("X-Request-ID", "abc123") .body(Map.of("message", "Processing")); follows correct chaining and uses Map.of for body. return ResponseEntity.body(Map.of("message", "Processing")) .header("X-Request-ID", "abc123") .status(HttpStatus.ACCEPTED); calls body() first, invalid order. return new ResponseEntity<>(Map.of("message", "Processing"), HttpStatus.ACCEPTED, Map.of("X-Request-ID", "abc123")); uses a constructor with three arguments which does not exist. return ResponseEntity.create(HttpStatus.ACCEPTED, Map.of("message", "Processing")) .header("X-Request-ID", "abc123"); uses a non-existent create() method.Final Answer:return ResponseEntity.status(HttpStatus.ACCEPTED) .header("X-Request-ID", "abc123") .body(Map.of("message", "Processing")); -> Option AQuick Check:status() -> header() -> body() chaining [OK]Quick Trick: Chain status(), then header(), then body() for full control [OK]Common Mistakes:Calling body() before status()Using non-existent ResponseEntity constructorsTrying to use create() method which doesn't exist
Master "REST Controllers" in Spring Boot9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallPerf
More Spring Boot Quizzes Application Configuration - application.yml alternative - Quiz 12easy Exception Handling - Custom exception classes - Quiz 3easy Exception Handling - Validation error responses - Quiz 2easy Exception Handling - Validation error responses - Quiz 3easy Logging - Log formatting configuration - Quiz 1easy Request and Response Handling - Request mapping by method and path - Quiz 4medium Request and Response Handling - Request validation preview - Quiz 1easy Spring Boot Fundamentals - POM.xml and dependencies - Quiz 14medium Spring Boot Fundamentals - Project structure walkthrough - Quiz 13medium Spring Boot Fundamentals - Why Spring Boot over plain Spring - Quiz 9hard