Spring MVC request flow
Every HTTP request goes through one front controller, the DispatcherServlet:
- Servlet filters run first (security, CORS, logging).
DispatcherServletasks a HandlerMapping which controller method matches the URL and HTTP method.- Interceptors'
preHandlemethods run. - A HandlerAdapter calls the method, resolving arguments such as
@PathVariable,@RequestParamand@RequestBody(converted from JSON by HttpMessageConverters). - The return value is written as JSON (
@RestController) or resolved to a view by a ViewResolver (for example Thymeleaf). - Exceptions go to
@ExceptionHandlermethods and@ControllerAdviceclasses.
@RestController is @Controller plus @ResponseBody.
Example
@RestController
@RequestMapping("/api/v1/courses")
public class CourseController {
private final CourseService service;
public CourseController(CourseService service) { this.service = service; }
@GetMapping
public Page<CourseDto> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(required = false) Level level) {
return service.search(level, PageRequest.of(page, 20));
}
@GetMapping("/{slug}")
public CourseDto get(@PathVariable String slug) {
return service.bySlug(slug);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CourseDto create(@Valid @RequestBody CreateCourse cmd) {
return service.create(cmd);
}
}Common mistake
Returning JPA entities directly from controllers. Lazy associations trigger N+1 queries or LazyInitializationException during JSON serialization, and you leak internal fields. Return DTOs instead.
Under the hood
Filters live at the servlet level, before Spring MVC; interceptors live inside Spring MVC and can see which handler was chosen. Spring Framework 7 adds first-class API versioning, selected by header, path or query parameter through a version attribute on the mapping annotations. Spring MVC is blocking (thread per request, which virtual threads now make cheap); WebFlux is the reactive, non-blocking alternative.
Check yourself
Which component converts a Java object to JSON in Spring MVC?
How this connects
Know these first
Where this leads
Part of Job-ready backend developer.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.