Câu hỏi phỏng vấn Spring
Câu hỏi

Explain the @Controller annotation.

Câu trả lời

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:

Definition 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].

Relationship with @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:

public class HelloController {
    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.

Functionality and Features

  • Handler Methods: Inside a controller, methods can handle requests and generate responses. These methods can have flexible signatures and can return different types of values including 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].
  • Model Integration: Controllers can add attributes to a model, which are then accessible wit...


Gợi ý câu hỏi phỏng vấn


Is the DispatcherServlet instantiated via an application context?


What is Spring MVC framework?


What are Spring beans?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào