Bird
0
0

Which of the following Spring Boot controller methods correctly handles a GET request to /item/{id} and returns the id as part of the response string?

hard📝 Application Q8 of 15
Spring Boot - REST Controllers
Which of the following Spring Boot controller methods correctly handles a GET request to /item/{id} and returns the id as part of the response string?
A@GetMapping("/item/{itemId}") public String getItem(@PathVariable int id) { return "Item ID: " + id; }
B@GetMapping("/item") public String getItem(@RequestParam String id) { return "Item ID: " + id; }
C@GetMapping("/item/{id}") public String getItem(@PathVariable String id) { return "Item ID: " + id; }
D@GetMapping("/item/{id}") public String getItem(@RequestBody String id) { return "Item ID: " + id; }
Step-by-Step Solution
Solution:
  1. Step 1: Match URL path variable

    The URL path variable is {id}, so the method parameter must be annotated with @PathVariable and named id or explicitly specify the variable name.
  2. Step 2: Check method signature

    @GetMapping("/item/{id}") public String getItem(@PathVariable String id) { return "Item ID: " + id; } correctly uses @GetMapping("/item/{id}") and @PathVariable String id, returning the id in the response.
  3. Step 3: Identify errors in other options

    @GetMapping("/item") public String getItem(@RequestParam String id) { return "Item ID: " + id; } uses @RequestParam which is for query parameters, not path variables. @GetMapping("/item/{itemId}") public String getItem(@PathVariable int id) { return "Item ID: " + id; } mismatches the path variable name itemId with parameter id without specifying the name in @PathVariable. @GetMapping("/item/{id}") public String getItem(@RequestBody String id) { return "Item ID: " + id; } incorrectly uses @RequestBody which is for request bodies, not path variables.
  4. Final Answer:

    @GetMapping("/item/{id}") public String getItem(@PathVariable String id) { return "Item ID: " + id; } correctly handles the GET request with path variable id.
  5. Quick Check:

    Path variable name matches and annotation correct [OK]
Quick Trick: Use @PathVariable with matching names for path params [OK]
Common Mistakes:
  • Using @RequestParam instead of @PathVariable for path variables
  • Mismatching path variable names and method parameters
  • Using @RequestBody for path variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes