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:
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.
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.
Final Answer:
Use two methods with @RequestMapping(path = "/items", method = RequestMethod.GET) and @RequestMapping(path = "/items", method = RequestMethod.POST). -> Option A
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
Master "Request and Response Handling" in Spring Boot
9 interactive learning modes - each teaches the same concept differently