Databases, Spring and microservices · 2. Spring Core and Spring MVC, lesson 8 of 8

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.

Diagram

Filters vs interceptors

Servlet filters run before the DispatcherServlet and see every request, including static files and errors; Spring Security is built from filters. HandlerInterceptors run inside Spring MVC, around controller methods, and know which handler was chosen (preHandle, postHandle, afterCompletion). Use a filter for low-level concerns (security, request IDs, compression) and an interceptor for MVC-aware ones (locale, per-controller auditing).

Validation and consistent errors

Annotate request DTOs with Bean Validation constraints and add @Valid to the parameter; invalid input throws MethodArgumentNotValidException. Handle exceptions in one place with @RestControllerAdvice and return RFC 9457 ProblemDetail responses, so every error has the same shape.

Java
record CreateCourse(@NotBlank String title, @Positive long pricePaise) {}

@PostMapping("/api/courses")
ResponseEntity<CourseView> create(@RequestBody @Valid CreateCourse body) { /* … */ }

@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail invalid(MethodArgumentNotValidException e) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Some fields are invalid");
        pd.setProperty("fields", e.getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, f -> String.valueOf(f.getDefaultMessage()), (a, b) -> a)));
        return pd;
    }
}

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.