Junior — Middle
Can you explain the role of the Controller within the Spring architecture and how it handles incoming requests?
sobes.tech AI
Answer from AI
In Spring architecture, the Controller is responsible for handling incoming HTTP requests and forming responses. It acts as an intermediary between the client and the application's business logic.
Main functions of the Controller:
- Receiving and recognizing HTTP requests (GET, POST, etc.) using annotations such as
@GetMapping,@PostMapping. - Extracting request parameters, body, headers.
- Calling the service layer to process data.
- Forming and returning a response to the client (e.g., JSON, HTML).
Example of a simple controller in Spring:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring!";
}
}
Here, @RestController combines @Controller and @ResponseBody, allowing data to be returned directly in the response body. The controller manages request routing and links requests to the appropriate handling methods.