@RequestMapping annotation is crucial in Spring Boot, primarily used for handling HTTP requests. It can be applied at the class level or method level. The main purpose of the @RequestMapping annotation is to serve as routing information, specifying which URLs map to which methods. When an HTTP request arrives at a Spring Boot application, Spring locates the corresponding method using @RequestMapping or its derived annotations and invokes it.
Main Functions
- Routing: Maps the request URL to a class or method.
- Method Specification: Allows specifying HTTP methods (GET, POST, PUT, etc.), beyond just the URL.
- Request Parameter and Header Mapping: Enables specifying required parameters or header information in the request via annotations.
Usage Example
Suppose we are developing an e-commerce platform and need to design an API to retrieve product details. We can use @RequestMapping in the controller to achieve this:
javaimport org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { @RequestMapping(value = "/product/{id}", method = RequestMethod.GET) public Product getProductById(@PathVariable String id) { // Logic processing, e.g., retrieving product information from the database return productService.getProductById(id); } }
In this example, the @RequestMapping annotation tells Spring Boot that the URL /product/{id} should be mapped to the getProductById method. The {id} in the URL represents a dynamic segment, which can be accessed using @PathVariable. This approach provides a flexible and powerful routing mechanism, enabling developers to easily design RESTful APIs.