What is the role of the @RequestMapping annotation in Spring MVC?

What is the role of the @RequestMapping annotation in Spring MVC?

A) To map web requests to specific handler methods
B) To define beans in the Spring context
C) To configure database connections
D) To initialize Spring Boot applications

Answer:

A) To map web requests to specific handler methods

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.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top