Spring MVC request architecture
Một HTTP request đi qua nhiều boundary trước controller. Hiểu đúng pipeline giúp đặt authentication, logging, binding, validation và error mapping vào đúng layer.
Front Controller pipeline
Servlet container chạy Filters rồi chuyển request vào DispatcherServlet. DispatcherServlet dùng các strategy interfaces để tìm handler, gọi controller, xử lý exception và tạo response.
| Thành phần | Vai trò |
|---|---|
HandlerMapping | Tìm handler và interceptors phù hợp request. |
HandlerAdapter | Biết cách thực thi loại handler đã chọn. |
HandlerMethodArgumentResolver | Tạo arguments cho controller method. |
HandlerExceptionResolver | Chuyển exception thành model, view hoặc HTTP response. |
HttpMessageConverter | Đọc/ghi body theo media type. |
ViewResolver | Resolve view cho mô hình MVC server-rendered. |
Argument resolution, binding và validation
Argument resolvers tạo path, query, header, body, principal hoặc pagination arguments. DataBinder chuyển text thành type; Validator kiểm tra constraints. Request body thường chỉ đọc được một lần, nên filter muốn log body phải dùng wrapper hoặc caching và phải redact dữ liệu nhạy cảm.
Return value và content negotiation
ResponseEntity điều khiển status, headers và body; converter được chọn theo Content-Type và Accept. Jackson configuration ảnh hưởng enum, date, null và unknown fields. Dùng DTO để tách transport contract khỏi entity, persistence context và lazy proxy.
Error contract
@ExceptionHandler hoặc @ControllerAdvice map domain/application exception thành error contract ổn định. Không catch mọi exception trong controller. Validation response không lộ stack trace hoặc internal field; correlation/trace ID giúp nối response với log và telemetry.
Filter, interceptor và advice
| Layer | Dùng cho | Caveat |
|---|---|---|
| Servlet Filter | Request/response boundary, encoding, correlation, security chain. | Có thể chạy cho async/error dispatch; cần cấu hình dispatch types đúng. |
| HandlerInterceptor | Logic quanh handler đã được resolve. | Không thay security filter chain; async lifecycle có callback bổ sung. |
| ControllerAdvice | Binding, exception và response concerns ở MVC. | Không xử lý lỗi xảy ra trước DispatcherServlet. |
Async MVC
Callable, DeferredResult hoặc CompletableFuture có thể giải phóng servlet thread trong lúc chờ, nhưng work vẫn cần executor, timeout và cancellation policy. Streaming hoặc SSE phải xử lý client disconnect, buffering và backpressure giới hạn của servlet stack. Async dispatch cũng làm filter/interceptor lifecycle chạy thêm pha.
Upload và static resources
Giới hạn multipart size, sanitize filename, lưu ngoài web root, scan content và không tin MIME type từ client. Với static hoặc range resource, thiết lập cache headers và content disposition đúng để tránh stale data hoặc content-sniffing risk.