What is the purpose of the @Controller annotation in Spring MVC?
Answer:
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.