What does @Controller annotation?
The @Controller
annotation is part of the Spring Framework, specifically within the Spring MVC (Model-View-Controller) module. It is used to indicate that a particular class serves as a controller in the MVC architecture. Here’s a breakdown of its purpose and functionality:
@Controller
Component Scanning: When you annotate a class with @Controller
, it becomes a candidate for component scanning. This means that Spring will automatically detect this class during the component scanning process and register it as a Spring bean in the application context.
Handling Requests: Classes annotated with @Controller
are typically used to handle web requests. They contain methods that are mapped to specific URL patterns, allowing them to respond to HTTP requests (GET, POST, etc.).
Returning Views: In a typical Spring MVC application, methods in a controller class can return a view name (e.g., a JSP page or a Thymeleaf template) that should be rendered in response to a request. The view resolver will then resolve this view name to the actual view.
Model Binding: Controllers can also handle data binding, where they can accept input from web forms and bind it to Java objects (models). This is often done using @ModelAttribute
or method parameters.
Here’s a simple example of a Spring MVC controller using the @Controller
annotation:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.ui.Model;
@Controller
@RequestMapping("/greeting")
public class GreetingController {
@GetMapping
public String greeting(Model model) {
model.addAttribute("message", "Hello, World!");
return "greeting"; // This will resolve to a view named "greeting"
}
}
@Controller
is a specialization of the @Component
annotation, which means it inherits all the characteristics of a Spring component.@RequestMapping
, @GetMapping
, @PostMapping
, etc., to specify the URL patterns that the controller methods should handle.In summary, the @Controller
annotation is a fundamental part of building web applications with Spring MVC, allowing developers to create structured and maintainable web applications by separating concerns between the controller, model, and view.