Junior — Middle
Can you explain what the @Controller annotation signifies in the context of web development?
sobes.tech AI
Answer from AI
The @Controller annotation in Java web development is used within the Spring Framework to denote a class that handles HTTP requests and returns responses.
Main points:
- A class with
@Controlleris considered an MVC (Model-View-Controller) component. - It accepts requests from clients, processes them, and returns a model and view name for rendering.
- Methods inside the class are usually annotated with
@RequestMappingor similar to specify which URLs they handle.
Example:
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello, world!");
return "helloView"; // view name
}
}
Here, when accessing /hello, the sayHello method is invoked, which adds data to the model and returns the view name for display to the user.
Thus, @Controller helps define controllers that manage the flow of data between the model and view in a web application.