REST: controllers and the request lifecycle
- REST
- Representational State Transfer
Junior Always asked 6 min
On this page
The question
What happens to an HTTP request in a Spring Boot REST application, from arrival to response?
30-second answer
It passes through servlet filters to DispatcherServlet. HandlerMapping finds the controller method, interceptors run preHandle, and argument resolvers bind and validate the input. Your method runs, and an HttpMessageConverter writes the result as JSON. Interceptors and filters then finish on the way out. If the controller throws, @RestControllerAdvice maps the exception to a response.
Understand it
An HTTP request through Spring MVC
Step by stepThe request enters the servlet filters first: logging, CORS, security. They wrap everything and can answer without ever reaching Spring MVC.
View as text
Seven stations in a column: servlet filters, DispatcherServlet, HandlerMapping, interceptor preHandle, binding and validation, your controller, and the controller advice. A marker shows where the request is, and a mark gives the current result.
The request enters the servlet filters first: logging, CORS, security. They wrap everything and can answer without ever reaching Spring MVC.
DispatcherServlet is the front controller. Every request that passes the filters goes through this one servlet, which coordinates the rest.
HandlerMapping finds the controller method from the URL and HTTP method. A DELETE on a GET-only path stops here with 405.
A HandlerInterceptor runs preHandle. Spring MVC knows the handler by now, so this suits checks that depend on the controller.
Argument resolvers read path variables and JSON, then @Valid checks the object. A failure returns 400, and the controller never runs.
Your method runs and calls the services. With @RestController, an HttpMessageConverter writes the return value as JSON.
postHandle and afterCompletion run, then the filters finish on the way out. The client receives 200 with a JSON body.
If the controller throws, @RestControllerAdvice maps the exception to a response, here 404. postHandle is skipped; afterCompletion still runs.
An exception thrown in a filter never reaches the advice, because Spring MVC has not started. The client gets a plain 500.
Seven stations in a column: servlet filters, DispatcherServlet, HandlerMapping, interceptor preHandle, binding and validation, your controller, and the controller advice. A marker shows where the request is, and a mark gives the current result.
The request enters the servlet filters first: logging, CORS, security. They wrap everything and can answer without ever reaching Spring MVC.
DispatcherServlet is the front controller. Every request that passes the filters goes through this one servlet, which coordinates the rest.
HandlerMapping finds the controller method from the URL and HTTP method. A DELETE on a GET-only path stops here with 405.
A HandlerInterceptor runs preHandle. Spring MVC knows the handler by now, so this suits checks that depend on the controller.
Argument resolvers read path variables and JSON, then @Valid checks the object. A failure returns 400, and the controller never runs.
Your method runs and calls the services. With @RestController, an HttpMessageConverter writes the return value as JSON.
postHandle and afterCompletion run, then the filters finish on the way out. The client receives 200 with a JSON body.
If the controller throws, @RestControllerAdvice maps the exception to a response, here 404. postHandle is skipped; afterCompletion still runs.
An exception thrown in a filter never reaches the advice, because Spring MVC has not started. The client gets a plain 500.
Takeaway: Filters wrap DispatcherServlet, which finds the handler, binds and validates arguments, and calls your method. Advice handles what controllers throw, but not what filters throw.
Map what happened to a status code
BuildEight things can happen to a request. Put each one on the status code a good API returns for it.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
- Empty
- Empty
- Empty
- Empty
View as text
A table of eight status codes, each with an empty slot. Eight things can happen to a request. Put each one on the status code a good API returns for it.
201 Created: New order saved. 400 Bad Request: Quantity fails @Min(1). 401 Unauthorized: Request has no token. 403 Forbidden: Valid token, scope missing. 404 Not Found: Order id does not exist. 405 Method Not Allowed: DELETE on a GET-only path. 409 Conflict: Email already registered. 500 Internal Server Error: Unhandled NullPointerException.
Created is 2xx. Client mistakes are 4xx, each with its own meaning. Only a bug on your side is a 500.
A table of eight status codes, each with an empty slot. Eight things can happen to a request. Put each one on the status code a good API returns for it.
201 Created: New order saved. 400 Bad Request: Quantity fails @Min(1). 401 Unauthorized: Request has no token. 403 Forbidden: Valid token, scope missing. 404 Not Found: Order id does not exist. 405 Method Not Allowed: DELETE on a GET-only path. 409 Conflict: Email already registered. 500 Internal Server Error: Unhandled NullPointerException.
Created is 2xx. Client mistakes are 4xx, each with its own meaning. Only a bug on your side is a 500.
Takeaway: A status code tells the client what to do next. 401 means authenticate, 403 means you may not, 409 means a conflict, and only your own bug is a 500.
In code
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService service;
OrderController(OrderService service) {
this.service = service;
}
@GetMapping("/{id}")
OrderDto get(@PathVariable long id) {
return service.find(id);
}
@PostMapping
ResponseEntity<OrderDto> create(@Valid @RequestBody NewOrder body) {
OrderDto created = service.place(body);
return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
}
}
record NewOrder(@NotBlank String sku, @Min(1) int quantity) {}@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
@ExceptionHandler(DuplicateEmailException.class)
@ResponseStatus(HttpStatus.CONFLICT)
ProblemDetail conflict(DuplicateEmailException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
}
}@GetMapping
PagedModel<OrderDto> list(@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
return new PagedModel<>(service.list(pageable)); // GET /orders?page=2&size=50&sort=total,asc
}Solve it
Design the endpoint that cancels an order
An order can be cancelled until it ships. The interviewer asks for the URL, the method, the status codes for each outcome, and what happens when a client retries a cancel after a timeout.
- Model the action. Cancelling changes state and may trigger a refund, so it is not a plain field update.
POST /orders/{id}/cancelnames the action; aPATCHof the status also works if the team prefers. - Map every outcome to a status. 200 with the updated order, 404 for an unknown id, 409 Conflict when the order has already shipped.
- Make the retry safe. Cancelling an order that is already cancelled returns 200 with the same body: the call is idempotent and refunds once.
- Keep the controller thin. The service holds the rule;
@RestControllerAdvicemaps its exceptions to 404 and 409. - Check. One MockMvc test per row: success, unknown id, shipped and repeated cancel.
@PostMapping("/{id}/cancel")
OrderDto cancel(@PathVariable long id) {
return service.cancel(id); // 200 with the cancelled order
}
@Transactional
public OrderDto cancel(long id) {
Order order = orders.findById(id).orElseThrow(() -> new OrderNotFoundException(id)); // 404
if (order.status() == Status.CANCELLED) return OrderDto.from(order); // idempotent retry
if (order.status() == Status.SHIPPED) throw new OrderAlreadyShippedException(id); // 409
order.cancel();
refunds.refund(order);
return OrderDto.from(order);
}
@ExceptionHandler(OrderAlreadyShippedException.class)
ProblemDetail shipped(OrderAlreadyShippedException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
}How to answer
- Filters belong to the servlet container and wrap all of Spring MVC (Model-View-Controller).
- Validation fails before the controller runs, as a 400.
- An exception in a filter does not reach
@RestControllerAdvice. - Jackson does the JSON work through a message converter.
Common mistakes
- Saying the controller receives the request directly from Tomcat.
- Claiming
@ControllerAdvicecatches exceptions thrown by a servlet filter.
Follow-up questions
What does @RestController do that @Controller does not?
@RestController is @Controller plus @ResponseBody. Every return value is written to the response body through a message converter, usually as JSON, and no view is resolved. Use ResponseEntity when you need to set the status or headers yourself, as in a 201 with a Location header.
- A String from
@Controlleris a view name; from@RestControllerit is the body. @ResponseStatussets a fixed status on a method.- Return a DTO (data transfer object), not a JPA (Jakarta Persistence API) entity, to keep the API independent of the database.
See it in the infographic: An HTTP request through Spring MVC
How do you validate a request body in Spring Boot?
Add spring-boot-starter-validation, put Jakarta Validation constraints such as @NotBlank and @Min on the DTO, and mark the parameter @Valid. Spring validates after binding, and throws MethodArgumentNotValidException before your method runs, which becomes a 400. Handle it in @RestControllerAdvice for a clear list of field errors.
- Without
@Valid, the constraints are never checked. - Nested objects need
@Validon the field too. @Validatedon a class validates method parameters such as@PathVariable.
record NewOrder(@NotBlank String sku, @Min(1) int quantity) {}
@PostMapping
OrderDto create(@Valid @RequestBody NewOrder body) {
return service.place(body);
} See it in the infographic: An HTTP request through Spring MVC
What is @ControllerAdvice, and how do you use it for errors?
It is a class of cross-cutting controller logic, most often @ExceptionHandler methods that apply to every controller. A method maps an exception type to a response, so controllers stay clean, and every error has the same shape. @RestControllerAdvice adds @ResponseBody. ProblemDetail gives a standard RFC 9457 body.
- The most specific
@ExceptionHandlerwins. - A catch-all for
Exceptionalso catches Spring Security's access denied exception, turning a 403 into a 500. @ResponseStatuson the exception class is a simpler alternative with less control.
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException e) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
}
} See it in the infographic: An HTTP request through Spring MVC
Which HTTP status codes should a REST API return, and when?
200 for a successful read, 201 with Location for a created resource, 204 for success with no body. 400 for invalid input, 401 when authentication is missing or invalid, 403 when the caller is known but may not do it, 404 for an unknown resource, 409 for a conflict such as a duplicate. 500 means a bug on the server, and it should never be used for client errors.
- 401 means "who are you?", and 403 means "I know you, and no".
- 405 and 415 are produced by Spring MVC for you.
- Returning 200 with an error in the body breaks clients, caches and monitoring.
See it in the infographic: Map what happened to a status code
What is the difference between a filter and a HandlerInterceptor?
A filter belongs to the servlet container and wraps everything, including DispatcherServlet, so it can change the raw request or stop it early. An interceptor belongs to Spring MVC, runs inside DispatcherServlet, and knows which handler was chosen. Use filters for security, CORS (cross-origin resource sharing) and logging, and interceptors for logic tied to controllers.
- Filters run even for requests no controller matches.
- A wrong HTTP method passes the filters but never reaches
preHandle, because no handler was found. postHandleis skipped when the controller throws;afterCompletionis not.
See it in the infographic: An HTTP request through Spring MVC
Where does the JSON body get converted into a Java object?
In RequestResponseBodyMethodProcessor, the argument resolver for @RequestBody. It picks an HttpMessageConverter from the Content-Type, usually Jackson's, and reads the object. If @Valid is present, it validates next. A wrong Content-Type gives 415, and malformed JSON gives 400.
What thread handles the request?
One thread from Tomcat's pool handles it from start to finish, by default, so a slow call blocks that thread. This is why a transaction or a ThreadLocal works across the layers. Virtual threads, or WebFlux, change how many requests you can hold waiting.
What produces the default error JSON when nothing handles an exception?
The container forwards to /error, where Spring Boot's BasicErrorController writes the JSON with timestamp, status, error and path. It is a second dispatch through the application. Enable spring.mvc.problemdetails.enabled for RFC 9457 bodies on exceptions Spring MVC handles itself.
Check yourself
Show answers
- The client gets 400, and the controller method never runs.: Correct. Validation happens during argument binding, before your method is called.
- The method runs, and the constraint is reported in a field.: Incorrect. That needs a BindingResult parameter. Without one, Spring throws before calling the method.
- The client gets 500.: Incorrect. Spring MVC already maps this exception to 400, because it is the client's mistake.
Show answers
- 500: Correct. The advice lives inside Spring MVC, and the filter runs before it. Boot's error handling writes a 500.
- 404: Incorrect. The handler is never consulted, because the exception did not come from a controller.
- 200 with an empty body: Incorrect. An uncaught exception cannot produce a success response.
Show answers
- 403: Correct. The caller is known, and is not allowed. Sending the same token again will not help.
- 401: Incorrect. That is for missing or invalid credentials, and it tells the client to authenticate.
- 400: Incorrect. The request itself is well formed. The problem is the caller's permissions.