What is the role of @RequestMapping in Spring Boot?
In Spring Boot, the `@RequestMapping` annotation is a fundamental component for defining how HTTP requests are mapped to handler methods within a controller. It allows developers to specify the URL path, HTTP method, and other request parameters that a particular method or class should handle, effectively routing incoming web requests to the appropriate application logic.
Core Functionality: Mapping HTTP Requests
@RequestMapping serves as the primary mechanism for associating web requests with specific controller methods or even entire controller classes. When a request comes into a Spring Boot application, the DispatcherServlet uses the information provided by @RequestMapping to identify which method is responsible for processing that request.
It's highly flexible, allowing mapping based on URL paths, HTTP methods (GET, POST, PUT, DELETE, PATCH), request parameters, headers, and even content types (consumes/produces).
Usage Scenarios
Class-Level Mapping
When applied at the class level on a @Controller or @RestController, @RequestMapping specifies a base URI or path for all handler methods within that controller. This helps organize endpoints and avoid repetition.
@RestController
@RequestMapping("/api/products")
public class ProductController {
// All methods in this controller will have "/api/products" as a prefix
}
Method-Level Mapping
When applied to a specific method within a controller, @RequestMapping specifies the exact endpoint for that method. It can also define the HTTP method (e.g., GET, POST) to be handled, overriding or complementing a class-level mapping.
@RestController
@RequestMapping("/api/users")
public class UserController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getAllUsers() {
return "List of all users";
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getUserById(@PathVariable Long id) {
return "User with ID: " + id;
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String createUser() {
return "New user created";
}
}
Key Attributes of @RequestMapping
valueorpath: Defines the URI template(s) that the method handles. Can be an array for multiple paths.method: Specifies the HTTP request method(s) (e.g.,RequestMethod.GET,RequestMethod.POST). If not specified, it handles all HTTP methods.consumes: Specifies the media types that the controller method can consume (e.g.,"application/json","application/xml").produces: Specifies the media types that the controller method can produce (e.g.,"application/json","text/plain").params: Specifies request parameters that must be present or absent for the mapping to match (e.g.,"myParam=myValue","!myOtherParam").headers: Specifies request headers that must be present or absent for the mapping to match (e.g.,"Content-Type=application/json","!Accept").
Modern Alternatives and Best Practices
While @RequestMapping is powerful, Spring introduced more specific composed annotations as syntactic sugar for common HTTP methods. These are preferred for clarity and conciseness, especially in RESTful APIs:
@GetMapping(forRequestMethod.GET)@PostMapping(forRequestMethod.POST)@PutMapping(forRequestMethod.PUT)@DeleteMapping(forRequestMethod.DELETE)@PatchMapping(forRequestMethod.PATCH)
Using these specialized annotations makes the code more readable and explicitly communicates the intended HTTP operation for an endpoint.
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}") // Shorthand for @RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String getProduct(@PathVariable Long id) {
return "Product details for ID: " + id;
}
@PostMapping("/") // Shorthand for @RequestMapping(value = "/", method = RequestMethod.POST)
public String createProduct() {
return "Product created";
}
}
Conclusion
@RequestMapping is the cornerstone annotation in Spring Boot for routing web requests to specific controller methods. It provides comprehensive control over how HTTP requests are handled, allowing for flexible and robust endpoint definitions. While still fully functional, modern Spring development often favors more specific method-level annotations like @GetMapping for enhanced readability and expressiveness in RESTful API design.