What is the purpose of the @Controller annotation in Spring MVC?

What is the purpose of the @Controller annotation in Spring MVC?

A) To define a Spring bean
B) To indicate that a class serves as a web controller
C) To handle exceptions in a Spring application
D) To enable component scanning

Answer:

B) To indicate that a class serves as a web controller

Explanation:

The @Controller annotation in Spring MVC is used to indicate that a particular class serves as a web controller. This annotation is a specialization of the @Component annotation and is used to mark a class as a Spring MVC controller, meaning it can handle HTTP requests. Classes annotated with @Controller are automatically detected by Spring during component scanning and are typically used to map web requests to specific handler methods.

For example:


@Controller
public class MyController {

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}

In this example, MyController is a Spring MVC controller, and the home() method is mapped to handle GET requests to the /home URL. The method returns the name of the view to be rendered, in this case, “home”. The @Controller annotation is essential for building web applications with Spring MVC, as it defines the controller layer of the MVC architecture.

Reference links:

Spring Boot Tutorial

Leave a Comment

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

Scroll to Top