Request Mapping
Request mapping connects an HTTP request — method, path, headers, content type — to a Java method. Spring MVC builds a table of all mappings at startup and, for each request, picks the most specific match. This lesson covers the mapping annotations and how a REST resource is laid out.
The mapping annotations
| Annotation | HTTP method | Typical use |
|---|---|---|
@GetMapping |
GET | read a resource or a list |
@PostMapping |
POST | create a resource |
@PutMapping |
PUT | replace a resource completely |
@PatchMapping |
PATCH | change part of a resource |
@DeleteMapping |
DELETE | remove a resource |
@RequestMapping |
any (configurable) | class-level prefix, or uncommon methods |
A resource controller
Put the common path prefix on the class with @RequestMapping, then map each operation:
@RestController
@RequestMapping("/api/tasks")
class TaskController {
private final TaskService service;
TaskController(TaskService service) { this.service = service; }
@GetMapping // GET /api/tasks
List<Task> list() { return service.findAll(); }
@GetMapping("/{id}") // GET /api/tasks/42
Task get(@PathVariable long id) { return service.get(id); }
@PostMapping // POST /api/tasks
@ResponseStatus(HttpStatus.CREATED)
Task create(@RequestBody NewTask body) { return service.create(body); }
@PutMapping("/{id}") // PUT /api/tasks/42
Task replace(@PathVariable long id, @RequestBody NewTask body) { return service.replace(id, body); }
@DeleteMapping("/{id}") // DELETE /api/tasks/42
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable long id) { service.delete(id); }
}This is the conventional REST layout: a plural noun for the collection, the id in the path for one item, and the HTTP method expresses the action — never /api/deleteTask?id=42.
Trying the endpoints
curl -s localhost:8080/api/tasks
echo
curl -s -X DELETE localhost:8080/api/tasks/1 -w "%{http_code}\n"
curl -s -X PATCH localhost:8080/api/tasks/2 -w "\n%{http_code}\n"[{"id":1,"title":"Learn Spring Boot","done":false},{"id":2,"title":"Write a controller","done":true}]
204
{"timestamp":"2025-10-16T03:31:09.874+00:00","status":405,"error":"Method Not Allowed","path":"/api/tasks/2"}
405
The path /api/tasks/2 exists, but no handler accepts PATCH, so Spring answers 405 Method Not Allowed (and lists allowed methods in the Allow header) instead of 404.
Matching on more than the path
Mappings can also require headers, parameters or content types:
@PostMapping(path = "/import", consumes = "text/csv")
ImportResult importCsv(@RequestBody String csv) { ... }
@GetMapping(path = "/{id}", produces = "text/plain")
String getAsText(@PathVariable long id) { ... }
@GetMapping(path = "/export", params = "format=pdf")
byte[] exportPdf() { ... }| Attribute | Matches | Failure status |
|---|---|---|
consumes |
request Content-Type |
415 Unsupported Media Type |
produces |
request Accept header |
406 Not Acceptable |
params |
query parameter present / has value | 400 or another handler |
headers |
request header present / has value | 404 |
How the best match is chosen
Spring compares all candidate patterns and prefers the more specific one: a literal path beats a variable, which beats a wildcard. The program below models this with a simple score (literal segments count most):
import java.util.*;
class Main {
record Route(String method, String pattern, String handler) {}
static boolean matches(String pattern, String path) {
String[] p = pattern.split("/"), s = path.split("/");
if (p.length != s.length && !pattern.endsWith("/**")) return false;
for (int i = 0; i < p.length; i++) {
if (p[i].equals("**")) return true;
if (i >= s.length) return false;
if (!p[i].startsWith("{") && !p[i].equals(s[i])) return false;
}
return true;
}
static int specificity(String pattern) {
int score = 0;
for (String seg : pattern.split("/")) {
if (seg.equals("**")) score += 0;
else if (seg.startsWith("{")) score += 1;
else score += 10;
}
return score;
}
static String dispatch(List<Route> routes, String method, String path) {
List<Route> pathMatches = routes.stream().filter(r -> matches(r.pattern(), path)).toList();
if (pathMatches.isEmpty()) return "404 Not Found";
return pathMatches.stream()
.filter(r -> r.method().equals(method))
.max(Comparator.comparingInt(r -> specificity(r.pattern())))
.map(r -> "200 -> " + r.handler())
.orElse("405 Method Not Allowed");
}
public static void main(String[] args) {
List<Route> routes = List.of(
new Route("GET", "/api/tasks", "list()"),
new Route("GET", "/api/tasks/{id}", "get(id)"),
new Route("GET", "/api/tasks/today", "today()"),
new Route("DELETE", "/api/tasks/{id}", "delete(id)"),
new Route("GET", "/docs/**", "docs()"));
String[][] requests = {
{"GET", "/api/tasks"}, {"GET", "/api/tasks/42"}, {"GET", "/api/tasks/today"},
{"DELETE", "/api/tasks/42"}, {"PATCH", "/api/tasks/42"}, {"GET", "/docs/api/intro"},
{"GET", "/api/users"}};
for (String[] r : requests) {
System.out.printf("%-6s %-18s %s%n", r[0], r[1], dispatch(routes, r[0], r[1]));
}
}
}GET /api/tasks 200 -> list()
GET /api/tasks/42 200 -> get(id)
GET /api/tasks/today 200 -> today()
DELETE /api/tasks/42 200 -> delete(id)
PATCH /api/tasks/42 405 Method Not Allowed
GET /docs/api/intro 200 -> docs()
GET /api/users 404 Not Found
/api/tasks/today matches both /api/tasks/today and /api/tasks/{id}; the literal one wins because it is more specific.
Note: Since Spring Framework 6, a trailing slash no longer matches by default:
/api/tasks/is not the same as/api/tasks. Be consistent in your clients.
Listing all mappings
With Actuator's mappings endpoint exposed you can inspect the real table:
curl -s localhost:8080/actuator/mappings \
| jq -r '.contexts.tasks.mappings.dispatcherServlets.dispatcherServlet[].predicate' | grep api{GET [/api/tasks]}
{GET [/api/tasks/{id}]}
{POST [/api/tasks]}
{PUT [/api/tasks/{id}]}
{DELETE [/api/tasks/{id}]}
Test yourself
Which annotation maps PATCH /api/tasks/{id}?
@PutMapping("/{id}")@PatchMapping("/{id}")@PostMapping("/{id}")@UpdateMapping("/{id}")
A path exists but only for GET. What does a DELETE to it return?
- 404 Not Found
- 405 Method Not Allowed
- 400 Bad Request
- 500 Internal Server Error
Both /api/tasks/{id} and /api/tasks/today are mapped. Which handles GET /api/tasks/today?
- The
{id}handler - The
todayhandler, because literal segments are more specific - Both
- Startup fails with an ambiguity error