3.3 Request Parameters & Payloads
← Back to Chapter 3: REST API & Web Layer
Controllers extract data from client requests across various parts of the HTTP protocol: path segments, query parameters, request headers, cookies, and the JSON payload body.
1. Parameter Extraction Annotations Matrix
| Annotation | HTTP Source | Example Usage |
|---|---|---|
@PathVariable | URI path template | /api/orders/{orderId} ➔ @PathVariable String orderId |
@RequestParam | Query parameter or form data | /search?q=java&page=2 ➔ @RequestParam String q |
@RequestBody | HTTP Request Payload Body (JSON/XML) | De-serializes payload via Jackson into Java POJO |
@RequestHeader | HTTP Inbound Headers | @RequestHeader("Authorization") String token |
@CookieValue | Inbound Cookies | @CookieValue(name = "sessionId") String sid |
2. Practical Endpoint Example
@RestController
@RequestMapping("/api/v1/orders")
public class OrderController {
@GetMapping("/search")
public Page<OrderResponse> searchOrders(
@RequestParam(name = "status", defaultValue = "PENDING") OrderStatus status,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = "20") int size,
@RequestHeader(name = "X-Correlation-Id", required = false) String correlationId
) {
Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
return orderService.findByStatus(status, pageable);
}
@PostMapping("/{customerId}/items")
public ResponseEntity<OrderResponse> placeOrder(
@PathVariable(name = "customerId") UUID customerId,
@Valid @RequestBody CreateOrderRequest request
) {
OrderResponse response = orderService.createOrder(customerId, request);
URI location = URI.create("/api/v1/orders/" + response.orderId());
return ResponseEntity.created(location).body(response);
}
}
3. Best Practice: Java Records as Immutable DTOs
Starting in Java 17+, using Java Records for request and response DTOs provides concise, immutable, and thread-safe data transfer:
public record CreateOrderRequest(
@NotBlank(message = "Item code cannot be blank")
String itemCode,
@Min(value = 1, message = "Quantity must be at least 1")
int quantity,
@NotNull(message = "Shipping address is mandatory")
AddressDTO shippingAddress
) {}
Jackson natively supports deserializing Java Records without needing getters, setters, or Lombok.