Chapter 6 of 12
Course Progress0 of 12 completed (0%)

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.

Building Production RESTful APIs with Spring MVCArchitect 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.UNDERSTANDBuilding RESTfulAPIsFOLLOW THE FLOWresilientAPPLY ITenterprise-readyHTTP RESTBuilding Production RESTful APIs with Spring MVCArchitect 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.UNDERSTANDBuilding RESTfulAPIsFOLLOW THE FLOWresilientAPPLY ITenterprise-readyHTTP REST

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:

1. HandlerMapping

Route Resolution

Inspects incoming URI paths, HTTP methods, and headers to match registered @GetMapping or @PostMapping methods.

2. HttpMessageConverter

JSON Deserialization

Jackson ObjectMapper reads the HTTP request InputStream and transforms JSON into Java records or DTOs.

3. HandlerAdapter

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);
    }
}
Concept Check

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

HTTP 200 OK: { "status": "FAIL", "errorMessage": "Invalid tax ID" }Inconsistent error schemas · 200 OK on failure breaks client retry logic

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

HTTP 400 Bad Request: { "type": "about:blank", "title": "Validation Failed", "status": 400, "invalidParams": [...] }RFC 7807 compliant · auto-parsed by OpenAPI tools and mobile SDKs

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
) {}
Concept Check

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

Spring MVC 6 / Spring Boot 3

Select HTTP Request Test Scenario:

POST
/api/v1/orders
Payload: { "customerId": "cust-842", "total": 149.50, "items": 3 }

Internal Pipeline Traversal:

1. Filter Chain

CorsFilter & Security headers passed

2. DispatcherServlet

Front controller receives HTTP request

3. HandlerMapping

Matches route to OrderController.createOrder()

4. MessageConverter

Jackson parses JSON into OrderRequest record

5. Jakarta @Valid

Validates @NotNull, @Positive — All Passed

6. Controller

Business logic creates order in database

Final HTTP Client Response
HTTP 201 Created
{
  "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:

Fix Missing Validation & Sensitive Exception Leak
Java

🎯 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 @Valid before @RequestBody UserDto request so 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:

Concept Check 1 of 2
1

What is the advantage of using RFC 7807 ProblemDetail in Spring Boot 3 over custom ErrorResponse classes?

Concept Check 2 of 2
2

What does @RestControllerAdvice combine?

8Recap

  • The DispatcherServlet directs incoming HTTP traffic through HandlerMapping, MessageConverters, and HandlerAdapters.
  • Always annotate request body DTO parameters with @Valid to 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:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us