@RequestMapping is the core Spring MVC annotation for binding incoming HTTP requests to specific handler methods. It declares which URL patterns and HTTP methods a controller or method should respond to, so DispatcherServlet knows exactly where to route each request.
Key Points: • It can be applied at the class level to define a shared base path and at the method level to define specific sub-paths and behavior. • The method attribute restricts a mapping to a particular HTTP verb, such as GET or POST. • More specific shortcut annotations like @GetMapping and @PostMapping are built on top of @RequestMapping for common cases. • It supports additional matching criteria — params, headers, consumes, produces — for fine-grained routing. • Without it, Spring has no way to know which method should handle which incoming URL and verb combination.
Example: @RequestMapping("/api/users") on a class combined with @RequestMapping(method = RequestMethod.GET) on a method means that class handles all requests under /api/users, and that specific method only responds to GET requests there.
Code Example:
@RequestMapping("/api/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public List<User> listUsers() { ... }
}Interview Tip: A concise interview answer is:
"@RequestMapping binds a URL pattern and HTTP method to a controller or handler method, which is how DispatcherServlet decides which code should run for a given request. It can be set at the class level for a shared base path and at the method level for specific routes, and the newer @GetMapping-style annotations are shorthand built on top of it."