Stage 10: Spring Core and Spring MVC, lesson 4 of 4

Spring MVC request flow

Intermediate3 min read@since 17Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Every HTTP request goes through one front controller, the DispatcherServlet:

  1. Servlet filters run first (security, CORS, logging).
  2. DispatcherServlet asks a HandlerMapping which controller method matches the URL and HTTP method.
  3. Interceptors' preHandle methods run.
  4. A HandlerAdapter calls the method, resolving arguments such as @PathVariable, @RequestParam and @RequestBody (converted from JSON by HttpMessageConverters).
  5. The return value is written as JSON (@RestController) or resolved to a view by a ViewResolver (for example Thymeleaf).
  6. Exceptions go to @ExceptionHandler methods and @ControllerAdvice classes.

@RestController is @Controller plus @ResponseBody.

Example

Java
@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

Part of Job-ready backend developer.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.