Java & Spring Boot Enterprise Mastery · Chapter 6 · ~15 min · Intermediate
Building Production RESTful APIs with Spring MVC
Architect resilient, enterprise-ready HTTP REST services. Trace the DispatcherServlet request pipeline, enforce declarative validation with Jakarta Bean Validation, and implement standardized RFC 7807 Problem Details with centralized exception handling.
- Trace HTTP request routing through DispatcherServlet and HandlerMapping
- Validate incoming request payloads using Jakarta Validation (@Valid, @NotNull)
- Implement standardized error responses with RFC 7807 Problem Details
- Construct global exception interceptors using @RestControllerAdvice
Building Production RESTful APIs with Spring MVC: learn it visually
Architect resilient, enterprise-ready HTTP REST services. Trace the DispatcherServlet request pipeline, enforce declarative validation with Jakarta Bean Validation, and implement standardized RFC 7807 Problem Details with centralized exception handling.
1The Front Controller Pattern: DispatcherServlet Pipeline
At the core of Spring MVC is the DispatcherServlet, implementing the classic Front Controller architectural pattern. Rather than registering individual servlets for every endpoint, all HTTP traffic flows into one centralized dispatcher that routes, adapts, and marshals responses:
Route Resolution
Inspects incoming URI paths, HTTP methods, and headers to match registered @GetMapping or @PostMapping methods.
JSON Deserialization
Jackson ObjectMapper reads the HTTP request InputStream and transforms JSON into Java records or DTOs.
Controller Invocation
Invokes the controller method with injected parameters, evaluates @Valid constraints, and catches any thrown exceptions.
// Modern Spring Boot 3 REST Controller with Immutability & Status Codes
@RestController
@RequestMapping("/api/v1/customers")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping
public ResponseEntity<CustomerResponse> createCustomer(
@Valid @RequestBody CreateCustomerRequest request,
UriComponentsBuilder ucb
) {
CustomerResponse created = customerService.create(request);
URI location = ucb.path("/api/v1/customers/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created);
}
}What is the primary role of the DispatcherServlet in a Spring Boot web application?
2Dual Mental Model: Ad-hoc Errors vs RFC 7807 with Global Advice
Compare the brittle practice of ad-hoc error DTOs and leaking stack traces against modern standardized RFC 7807 Problem Details:
Wrong idea: Ad-hoc arbitrary error JSON formats invented per developer
Returning inconsistent error payloads like { 'err': 'bad' }, { 'errorMsg': 'fail' }, or { 'status': 'failed' } with missing HTTP statuses.
Real system: Standardized RFC 7807 Problem Details for HTTP APIs
Emitting RFC 7807 ProblemDetail payloads with standardized URI type, title, status code, detail description, instance URI, and structured field violations.
3Declarative Payload Validation with Jakarta Bean Validation
Never write manual if (field == null) checks inside controller handlers. Java EE / Jakarta Bean Validation (jakarta.validation-api with Hibernate Validator) enables declarative, self-documenting data constraints directly on record fields:
public record CreateCustomerRequest(
@NotBlank(message = "Customer name must not be blank")
@Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters")
String fullName,
@NotBlank(message = "Email is required")
@Email(message = "Email must be a valid email address")
String email,
@NotNull(message = "Monthly spend limit is required")
@PositiveOrZero(message = "Spend limit cannot be negative")
BigDecimal monthlyLimit,
@Pattern(regexp = "^[A-Z]{2}[0-9]{2}[A-Z0-9]{4}[0-9]{7}([A-Z0-9]?){0,16}$", message = "Invalid IBAN format")
String bankIban
) {}What happens if you define validation constraints like @NotBlank on a DTO record but omit the @Valid annotation on the controller's @RequestBody parameter?
4Interactive Visualizer: DispatcherServlet Pipeline Simulator
Simulate how different HTTP requests traverse Spring MVC's pipeline, triggering message converters, validation errors, or global exception resolvers:
Spring MVC DispatcherServlet Pipeline Simulator
Trace an HTTP request packet through HandlerMapping, MessageConverters, Jakarta Validation, and @RestControllerAdvice
Select HTTP Request Test Scenario:
Internal Pipeline Traversal:
CorsFilter & Security headers passed
Front controller receives HTTP request
Matches route to OrderController.createOrder()
Jackson parses JSON into OrderRequest record
Validates @NotNull, @Positive — All Passed
Business logic creates order in database
{
"orderId": "ord-99014",
"status": "CONFIRMED",
"total": 149.50
}5Standardized Error Handling with RFC 7807 & @RestControllerAdvice
Spring Boot 3 natively supports RFC 7807 Problem Details for HTTP APIs through the ProblemDetail class. By pairing this with @RestControllerAdvice, your entire microservice emits clean, machine-readable errors without leaking internal stack traces:
@RestControllerAdvice
public class GlobalApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalApiExceptionHandler.class);
// 1. Handle Bean Validation Errors (400 Bad Request)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleValidationErrors(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"One or more input fields failed validation constraints"
);
problem.setTitle("Validation Failure");
problem.setType(URI.create("https://api.enterprise.com/errors/validation-failed"));
List<Map<String, String>> fieldErrors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(err -> Map.of("field", err.getField(), "message", err.getDefaultMessage()))
.toList();
problem.setProperty("invalidParameters", fieldErrors);
return problem;
}
// 2. Handle Resource Missing (404 Not Found)
@ExceptionHandler(EntityNotFoundException.class)
public ProblemDetail handleNotFound(EntityNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Resource Not Found");
return problem;
}
// 3. Catch-all: Safe 500 without leaking database details
@ExceptionHandler(Exception.class)
public ProblemDetail handleUncaught(Exception ex) {
log.error("Unhandled internal server exception", ex); // Log privately!
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR,
"An unexpected server error occurred. Please reference support ID: " + UUID.randomUUID()
);
problem.setTitle("Internal Server Error");
return problem;
}
}6Code Bug Hunt: Missing DTO Validation & Stack Trace Leak
The UserController below fails to trigger validation and throws a raw exception containing sensitive database details. Fix the controller to use declarative validation and remove the sensitive exception leak:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
Fix validation and exception handling in UserController:
- Add
@Validbefore@RequestBody UserDto requestso Spring MVC triggers Jakarta Bean Validation. - Remove the manual check that throws raw
RuntimeException("Database error: ...")to prevent database internal details from leaking to clients.
7Chapter Knowledge Challenge
Verify your understanding of Spring MVC and production API design:
What is the advantage of using RFC 7807 ProblemDetail in Spring Boot 3 over custom ErrorResponse classes?
What does @RestControllerAdvice combine?
8Recap
- The DispatcherServlet directs incoming HTTP traffic through HandlerMapping, MessageConverters, and HandlerAdapters.
- Always annotate request body DTO parameters with
@Validto activate Jakarta Bean Validation (@NotBlank,@Email,@Positive). - RFC 7807 ProblemDetail delivers standardized, machine-readable error responses across all APIs.
- Centralize error handling with
@RestControllerAdvice, logging internal stack traces privately to protect system internals while returning sanitized errors to clients.
Ready for Chapter 7? Mark this chapter as complete to proceed: