Foundation · Build

Request Data Binding

Each source of request data has its own annotation: identifiers from the path, options from the query string, metadata from headers, payload from the body.

Primary source: Spring MVC: Model Design and Data Binding

25 min

Lesson 4 of 11

1d streak

The Architectural Question

Swapping @PathVariable for @RequestParam changes where Spring looks for the value, producing immediate 400s that look like client bugs but are annotation mistakes.

What this guide proves

  • @PathVariable
  • @RequestParam
  • @RequestBody

The four HTTP transport binding channels

REST endpoints extract parameters from different parts of the incoming HTTP request. Spring MVC assigns specific annotations to each protocol channel, and choosing the wrong annotation leads to immediate 400 Bad Request errors.

AnnotationHTTP LocationTypical PurposeNullability Default
@PathVariableURI Path SegmentResource identity (e.g. /orders/{id})Required
@RequestParamQuery String / Form DataFiltering, pagination, flags (?status=ACTIVE)Required (required=true)
@RequestHeaderHTTP HeadersMetadata, tokens, tracing (X-Trace-Id)Required
@RequestBodyHTTP Request PayloadComplex JSON/XML object representationsRequired

How WebDataBinder converts strings into strongly-typed objects

Every path variable, query parameter, and header enters the web server as a raw String. Before your controller method executes, Spring’s WebDataBinder invokes the registered ConversionService to parse these strings into Java types.

  1. 01DispatcherServlet matches the request URI to a HandlerMethod.
  2. 02HandlerMethodArgumentResolver iterates over each method parameter.
  3. 03PathVariableMethodArgumentResolver extracts the URI template variable from the matching route pattern.
  4. 04ConversionService looks up a Converter<String, T> (e.g., String to UUID or String to Enum).
  5. 05If parsing fails (e.g. invalid UUID string), a MethodArgumentTypeMismatchException is raised before controller logic runs.

Binding multiple channels in one controller

ProductSearchController.java
package com.example.catalog.api;

import java.util.UUID;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/categories/{categoryId}/products")
public class ProductSearchController {

    @GetMapping
    public ResponseEntity<SearchResult> search(
            @PathVariable UUID categoryId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(required = false) String search,
            @RequestHeader("X-Request-Id") String requestId) {

        var result = new SearchResult(categoryId, page, search, requestId);
        return ResponseEntity.ok(result);
    }
}

record SearchResult(UUID categoryId, int page, String query, String traceId) {}

Break it deliberately: type mismatch vs missing parameter

When a client sends a malformed value or omits a required parameter, Spring halts processing at the adapter layer. Observe the difference between type mismatch and missing parameters:

Terminal / Diagnostic Output
Scenario A: Invalid UUID in path (/api/categories/not-a-uuid/products)
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.UUID'

Scenario B: Missing required header X-Request-Id
org.springframework.web.bind.MissingRequestHeaderException: Required request header 'X-Request-Id' for method parameter type String is not present

Active Recall Checkpoint

If a client passes an optional query parameter that might be empty, how should you declare it to avoid 400 Bad Request?

Hint: Consider required attributes or Java 8 types.

Show answer & explanation

Set @RequestParam(required = false) or provide a default with @RequestParam(defaultValue = "defaultVal"), or wrap the parameter in java.util.Optional<T>.

Production best practices for data binding

Use it when

Use @PathVariable for resource identity and @RequestParam for orthogonal filters, search queries, and pagination options.

Reconsider when

Never put sensitive credentials or massive arrays in query parameters; use @RequestBody with HTTPS to protect payload data.

Synthesis & Production Verification

Production Acceptance Criteria

  • Bind path segments, query parameters, headers, and body in one endpoint
  • Make a parameter optional explicitly and document the fallback
  • Explain how Jackson feeds @RequestBody deserialization

Architectural & Technical Review

Core Interview Questions

Q01When should you use @PathVariable versus @RequestParam?Show answer

Use @PathVariable for resource identity in the URI path and @RequestParam for filtering, pagination, and optional modifiers in query strings.

Q02How does WebDataBinder handle type conversion?Show answer

It delegates to ConversionService to parse String parameters into target types (e.g. UUID, Enums), raising MethodArgumentTypeMismatchException on format errors.

Q03What HTTP status is returned when a required query parameter is missing?Show answer

Spring throws MissingServletRequestParameterException, which translates to an HTTP 400 Bad Request response.

Production Pitfalls

Critical Anti-Patterns

  • Pitfall: Passing sensitive credentials in query parameters — Query parameters leak in web server access logs, browser history, and HTTP referer headers; always pass credentials in headers or POST bodies.
  • Pitfall: Relying on implicit parameter names without compiler flags — Omitting annotation names requires compiling with the -parameters flag; specify explicit names or enable parameter retention.

Primary Documentation & Specifications

Supplementary Module Resources