Spring MVC Basics
What Spring MVC does
An HTTP server receives requests, but the application needs a convenient way to connect them to Java code. Spring MVC takes care of that task: based on the address and HTTP method, it finds a suitable handler, prepares its arguments, calls the method, and then turns the result into an HTTP response.
A controller remains a regular Spring bean. That means it can receive services through Dependency Injection and focus only on web-related tasks without creating dependencies manually.
@RestController
class GreetingController {
private final GreetingService greetingService;
GreetingController(GreetingService greetingService) {
this.greetingService = greetingService;
}
@GetMapping("/greeting")
String greeting() {
return greetingService.message();
}
}
Here Spring MVC connects the GET /greeting request to the
greeting() method. We will cover mapping, response bodies, and REST controllers on the next pages;
for now, the important idea is that an HTTP request becomes a call to a regular Java method.
Where the web layer ends
A controller is responsible for HTTP-related work: accepting request data, choosing an appropriate response form, and delegating the actual work. Business rules are better kept in services and other application components. This keeps the web layer thin and prevents the core logic from depending on a particular way of being called.