Skip to the page

Spring REST APIs · core

How a request reaches your controller, and validation

A request passes servlet filters, then DispatcherServlet, then your controller method. Validate the shape with Bean Validation and return a clear 400.

The notes

What you must know

  • @RestController = @Controller + @ResponseBody: return values are written to the body by message converters (JSON through Jackson).
  • Flow: Tomcat accepts the connection and a worker thread runs the servlet filters (security, CORS, logging), then DispatcherServlet, a HandlerMapping, argument resolution, your method, then a message converter.
  • Filters are servlet-level and run before Spring MVC. Spring Security lives there. Interceptors are Spring MVC-level and know which handler will run.
  • Malformed JSON gives HttpMessageNotReadableException (400). A failed @Valid @RequestBody gives MethodArgumentNotValidException (400).
  • Tomcat by default has 200 worker threads (server.tomcat.threads.max) unless virtual threads are on.
  • POST /orders: DTOs as records, with @NotNull, @NotEmpty, @Size and List<@Valid OrderLine>. Return ResponseEntity.created(location).body(...) for 201.
  • Bean Validation checks only the shape. Business checks (product exists, in stock) belong in the service: 404 or 422 with an error code.
  • If customers place their own orders, the customer id comes from the logged-in user, not the body. Test with a @WebMvcTest slice and MockMvc for 201 and 400, with the service replaced by @MockitoBean.

The red pen

Common traps: mistake → fix

  • Mistake: Filters and interceptors are the same

    Fix: filters run before Spring MVC; interceptors know the handler.

  • Mistake: @Valid checks that the product exists

    Fix: it checks only shape; business rules go in the service.

  • Mistake: The client can send the customer id

    Fix: take it from the authenticated user.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between @Controller and @RestController?
  2. Walk through what happens from the request arriving to your method running.
  3. Write POST /orders with validation. What do you return on success and on bad input?
  4. Filter or interceptor for logging a request id?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview