When building web applications in Spring, we need a way to map HTTP requests to handler methods in the controller. Without @RequestMapping
, it would be difficult to handle different URLs and HTTP methods in a structured way.
What is it?
@RequestMapping
is an annotation in Spring MVC used to map web requests (URLs) to specific handler methods in the controller class. It helps in defining which URLs should trigger a method and what HTTP methods (GET, POST, etc.) they should respond to.
How is it used?
You place @RequestMapping
above a method (or a class) to define the URL it should handle and optionally specify the HTTP method.
Example:
1. Basic Mapping:
java
@RequestMapping("/home")
public String home() {
return "This is the home page";
}
Maps the /home
URL to the home()
method.
- Mapping with HTTP Methods:
java
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitForm() {
return "Form submitted";
}
This method is invoked when the /submit
URL is accessed via a POST request.
@RequestMapping
helps organize and structure how HTTP requests are handled, improving code readability and maintainability.