Bird
0
0

You want to create two methods in a controller: one handles GET requests at "/items" and another handles POST requests at the same path "/items". Which is the best way to do this?

hard📝 Application Q15 of 15
Spring Boot - Request and Response Handling
You want to create two methods in a controller: one handles GET requests at "/items" and another handles POST requests at the same path "/items". Which is the best way to do this?
AUse two methods with @RequestMapping(path = "/items", method = RequestMethod.GET) and @RequestMapping(path = "/items", method = RequestMethod.POST).
BUse one method with @RequestMapping(path = "/items") and check HTTP method inside the method manually.
CUse @RequestMapping(path = "/items") on both methods without specifying method attribute.
DUse @RequestMapping(method = RequestMethod.GET) on one method and @RequestMapping(method = RequestMethod.POST) on the other without path.
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to map same path with different methods

    Spring allows multiple methods mapped to the same path but different HTTP methods using method attribute.
  2. Step 2: Evaluate options

    Use two methods with @RequestMapping(path = "/items", method = RequestMethod.GET) and @RequestMapping(path = "/items", method = RequestMethod.POST). correctly uses two methods with same path but different HTTP methods. Use one method with @RequestMapping(path = "/items") and check HTTP method inside the method manually. is less clean and error-prone. Use @RequestMapping(path = "/items") on both methods without specifying method attribute. causes ambiguity. Use @RequestMapping(method = RequestMethod.GET) on one method and @RequestMapping(method = RequestMethod.POST) on the other without path. misses path, so won't map correctly.
  3. Final Answer:

    Use two methods with @RequestMapping(path = "/items", method = RequestMethod.GET) and @RequestMapping(path = "/items", method = RequestMethod.POST). -> Option A
  4. Quick Check:

    Separate methods with same path, different HTTP methods [OK]
Quick Trick: Map same path with different methods by specifying method attribute [OK]
Common Mistakes:
  • Not specifying method attribute causing conflicts
  • Checking HTTP method manually inside one method
  • Omitting path attribute causing mapping errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes