Explain the @Controller annotation.
Explain the @Controller annotation.
The @Controller
annotation in Spring Framework is a specialized stereotype annotation that marks a class as a Spring MVC controller. This annotation plays a crucial role in the development of web applications using Spring MVC. Here's a detailed explanation of its functionality and usage:
The @Controller
annotation indicates that a particular class serves as a controller in the model-view-controller (MVC) architecture. It is only applicable to classes and is used to identify a component that will perform business logic and handle web requests. This annotation is a specialization of the @Component
annotation, allowing for the autodetection of controller classes through classpath scanning and automatic registration of bean definitions[2][3][5].
@RequestMapping
Typically, @Controller
is used in conjunction with @RequestMapping
or other mapping annotations like @GetMapping
, @PostMapping
, etc. These annotations are used to map web requests to specific handler methods within the controller class[1][3]. For example:
@Controller
public class HelloController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello World!");
return "helloView";
}
}
In this example, @GetMapping("/hello")
specifies that the sayHello
method should handle HTTP GET requests for the path /hello
. The @Controller
annotation declares that HelloController
is a Spring MVC controller.
ModelAndView
, String
, ResponseEntity
, etc., depending on what view technology is being used or if the response is more data-centric (e.g., REST APIs)[1].junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào