How can you define method-level mappings within a controller?

Method-level mappings let a single controller class expose multiple endpoints, each handled by its own method, by annotating each method with a request-mapping annotation that specifies a URL pattern and HTTP method. This keeps related endpoints grouped together while still routing each request precisely.

Key Points: • @RequestMapping can be combined with the method attribute (RequestMethod.GET, POST, etc.) to restrict a mapping to a specific HTTP verb. • Shortcut annotations @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping are the modern, more readable way to declare method-level mappings. • A class-level @RequestMapping can define a common base path, with each method appending its own sub-path. • Method-level mappings can also declare consumes/produces to restrict which content types they accept or return. • Overlapping mappings between methods cause an ambiguous mapping exception at startup, so each combination of path and HTTP method must be unique.

Example: A UserController might use a class-level @RequestMapping("/users") combined with @GetMapping("/{id}") for fetching a user and @PostMapping for creating one, keeping all user-related endpoints in one class.

Code Example:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) { ... }

    @PostMapping
    public User createUser(@RequestBody User user) { ... }
}

Interview Tip: A concise interview answer is:

"I define method-level mappings with @GetMapping, @PostMapping, and similar shortcut annotations, often combined with a class-level @RequestMapping base path. Each method's annotation specifies both the URL pattern and the HTTP verb it handles, so Spring can route each incoming request to exactly one method."