How does @RequestMapping handle different types of HTTP requests?

@RequestMapping handles different HTTP methods on the same URL by accepting a method attribute that restricts which verb (GET, POST, PUT, DELETE, etc.) a given handler method responds to.

Key Points: • Without a method attribute, @RequestMapping matches any HTTP verb for that path, which is usually too permissive for real endpoints. • Setting method = RequestMethod.GET or RequestMethod.POST scopes the mapping to only that verb. • Dedicated shortcut annotations — @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping — are the modern, more readable equivalent built on top of @RequestMapping. • Multiple methods on the same class can share the same path but differ by HTTP verb, letting one resource support full CRUD semantics. • Additional attributes like consumes and produces further narrow matching based on request/response content types.

Example: A REST controller for /items might have one method annotated @GetMapping("/items/{id}") to fetch an item and another annotated @PostMapping("/items") to create one, both technically expressible with @RequestMapping and an explicit method attribute.

Code Example:

@RequestMapping(value = "/example", method = RequestMethod.GET)
public String getExample() { ... }

@RequestMapping(value = "/example", method = RequestMethod.POST)
public String postExample() { ... }

Interview Tip: A concise interview answer is:

"@RequestMapping's method attribute lets you restrict a handler to a specific HTTP verb, so the same URL path can support GET, POST, PUT, and DELETE through different methods. In practice I use the shortcut annotations like @GetMapping and @PostMapping, which are just @RequestMapping preconfigured with that method attribute."