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.
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.
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
@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
Part of Job-ready backend developer.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.