Controller and request mapping
What you will learn
A REST controller translates an HTTP request into a domain operation and an explicit HTTP response. Keep the transport contract separate from storage details.
- Trace path, query and JSON body binding.
- Distinguish domain records and public DTOs.
- Explain 200 and 201 responses and Location.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. MVC examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Read a public DTO
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore(); var item = store.get("A1");System.out.println(item.sku() + ": " + item.name() + " / " + item.quantity());System.out.println(Arrays.stream(item.getClass().getRecordComponents()).map(c -> c.getName()).toList());} }Expected output:
A1: Notebook / 5[sku, name, quantity]The projection exposes exactly three record components, not the internal note. This is Java metadata, not a JSON serializer test.
Request dispatch
DispatcherServlet coordinates handler selection, argument resolution, invocation and message conversion. @RestController combines controller registration with response-body semantics; @RequestMapping supplies a common path, while @GetMapping and @PostMapping narrow the method. Path variables identify resources; query parameters modify a query; @RequestBody decodes a representation. The Content-Type describes the submitted representation; Accept describes acceptable response media. JSON conversion requires a configured converter.
Separate the contracts
The store owns internal entries and synchronization. The public Item record includes only sku, name and quantity; never serialize a persistence entity just because it has getters. A successful GET returns 200; creation uses 201 with a Location URI. A client cannot infer business success merely from JSON being parseable. The lab restricts SKUs to a URI-safe alphabet and uses a relative Location. Authentication and authorization are not implemented.
Create and read back
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore(); var item = store.create("D4", "Eraser", 3);System.out.println("/api/v1/items/" + item.sku());System.out.println(store.get("D4").quantity());} }Expected output:
/api/v1/items/D43The validated SKU can form this path. The HTTP adapter, not the store, sets status and Location.
Boot registration
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/src/main/java/example/inventory/InventoryApp.java; use the companion lab README.
package example.inventory;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class InventoryApp { public static void main(String[] args) { SpringApplication.run(InventoryApp.class, args); } @Bean InventoryStore inventoryStore() { return new InventoryStore(); }}Predicted behavior: A context registers one store.
The store is a bean, not a controller.
HTTP adapter
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/src/main/java/example/inventory/InventoryController.java; use the companion lab README.
package example.inventory;import java.net.URI;import jakarta.validation.Valid;import org.springframework.http.*;import org.springframework.web.bind.annotation.*;@RestController@RequestMapping(value="/api/v1/items", produces=MediaType.APPLICATION_JSON_VALUE)public class InventoryController { private final InventoryStore store; public InventoryController(InventoryStore store) { this.store = store; } @GetMapping("/{sku}") public InventoryStore.Item get(@PathVariable("sku") String sku) { return store.get(sku); } @PostMapping(consumes=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<InventoryStore.Item> create(@Valid @RequestBody CreateItem body) { var item = store.create(body.sku(), body.name(), body.quantity()); return ResponseEntity.created(URI.create("/api/v1/items/" + item.sku())).body(item); } @GetMapping public InventoryStore.Page list(@RequestParam(name="page",defaultValue="0") int page, @RequestParam(name="size",defaultValue="20") int size, @RequestParam(name="sort",defaultValue="sku") String sort) { return store.page(page, size, sort); }}Predicted behavior: GET returns a DTO; POST creates and returns 201 with Location.
Explicit parameter names avoid relying on compiler parameter metadata.
Common mistakes
Do not accept or return internal entities, put state changes in GET, or confuse request Content-Type with Accept. Avoid automatic retries of non-idempotent POST without a designed retry protocol.
Practice
Create SKU E5, name Ruler, quantity 4; print its path and read-back name.
Expected output:
/api/v1/items/E5RulerCompare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Controller and request mapping — knowledge check
REST API engineering and HTTP contract reasoning.
Which annotation binds a resource identifier in the URL?
Which header describes the submitted JSON representation?
Which status best fits a newly created resource?
Why return a separate Item DTO?
What should GET do?