@RequestMapping
is a versatile annotation used in Spring MVC to map HTTP requests to handler methods in controller classes. It allows developers to define URL patterns and associate them with specific controller methods, specifying how incoming requests should be handled.
Here are the key features and uses of @RequestMapping
:
- Mapping URLs:
@RequestMapping
is used to map HTTP requests to specific URLs or URL patterns.- It can be applied at the class level to define a base URL for all handler methods within the controller, as well as at the method level to define more specific mappings.
- HTTP Methods:
@RequestMapping
supports mapping requests to specific HTTP methods (e.g., GET, POST, PUT, DELETE) using themethod
attribute.- If no specific HTTP method is specified, the mapping applies to all HTTP methods by default.
- Path Variables:
@RequestMapping
supports path variables, which allow dynamic parts of the URL to be extracted and passed as method parameters.- Path variables are defined within curly braces
{}
in the URL pattern and are mapped to method parameters using@PathVariable
annotation.
- Request Parameters:
@RequestMapping
can map requests based on request parameters using theparams
attribute.- Request parameters can be specified as key-value pairs (e.g.,
"paramName=value"
) or as boolean expressions (e.g.,"paramName"
) to check for the presence or absence of a parameter.
- Headers and Consumes/Produces:
@RequestMapping
supports mapping requests based on request headers using theheaders
attribute.- It also supports mapping requests based on the content type of the request (
consumes
) and the content type of the response (produces
).
- Content Negotiation:
@RequestMapping
supports content negotiation, allowing the same URL to handle requests with different content types (e.g., JSON, XML).- Content negotiation is based on the
produces
attribute, which specifies the supported media types for the response.
- Fallback and Default Mapping:
@RequestMapping
can be used as a fallback mapping for requests that do not match any specific mappings.- It can also be used to define default mappings for controller methods that handle requests for the root URL or when no specific path is provided.
Example usage of @RequestMapping
:
@Controller
@RequestMapping("/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
// Method logic to retrieve product by ID
}
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
// Method logic to create a new product
}
}
In this example, @RequestMapping
is used at the class level to specify the base URL /products
for all handler methods within the ProductController
class. The @GetMapping
and @PostMapping
annotations are used at the method level to further define specific URL mappings for handling GET and POST requests, respectively.