What is the role of the @RequestMapping annotation in Spring MVC?
Answer:
Explanation:
The @RequestMapping
annotation in Spring MVC is used to map web requests to specific handler methods within a controller. This annotation can be applied at the class level to define a base URL for all methods within the controller, or at the method level to map individual HTTP requests to specific handler methods.
For example:
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/profile")
public String userProfile() {
return "profile";
}
}
In this example, the @RequestMapping("/user")
annotation at the class level defines a base URL for all methods within the UserController
class. The userProfile()
method is then mapped to handle requests to /user/profile
. The method returns the name of the view to be rendered, “profile”. The @RequestMapping
annotation is versatile and can be used to handle different HTTP methods (GET, POST, etc.), specify request parameters, headers, and more.