Sub topic 2
Controllers and Request Mappings
This chapter covers how Spring Boot decides which Java method handles an incoming HTTP request. Later chapters bind data to that method's parameters. Here the focus is on the method itself and the rules that select it.
Prerequisites assumed: basic Java including classes and records, a Spring Boot project that includes spring-boot-starter-web and starts, basic HTTP knowledge (methods, status codes, headers), and basic JSON syntax.
What a controller is
A controller is a Spring-managed class whose methods handle HTTP requests. Spring Web MVC routes each request through a component called the DispatcherServlet. It is the single entry point for all requests. It asks a registry of handler mappings which method matches the request, calls that method, and then writes the return value into the response.
Two steps in this flow matter for the rest of the tutorial. Argument binding turns parts of the request into method parameters. Message conversion turns the return value into the response body, usually JSON.
@RestController
The annotation @RestController marks a class as a controller whose return values become the response body. It combines two annotations:
@Controllerregisters the class as a Spring bean that handles web requests.@ResponseBodytells Spring to serialize each return value into the response, instead of treating it as a view name.
Use @RestController for JSON APIs. If you use plain @Controller and forget @ResponseBody, Spring tries to resolve the returned object as a template name. The usual symptom is a 404 or a template-resolution error instead of JSON.
@RequestMapping on a class
@RequestMapping declares which requests a class or method handles. On a class, it sets a prefix that every method inherits.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
}Every handler method in this class now has a path that starts with /api/books. The constructor takes BookService, and Spring injects it. With a single constructor, no @Autowired is needed.
Method-level shortcuts
On a method, you combine the HTTP method and the remaining path. The long form is @RequestMapping(method = RequestMethod.GET, path = "/{id}"). Spring provides shortcut annotations that say the same thing:
| Annotation | HTTP method | Typical use |
|---|---|---|
| `@GetMapping` | GET | Read a resource or a list |
| `@PostMapping` | POST | Create a resource |
| `@PutMapping` | PUT | Replace a resource |
| `@PatchMapping` | PATCH | Change part of a resource |
| `@DeleteMapping` | DELETE | Remove a resource |
The class prefix and the method path are joined. This method answers GET /api/books/42:
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}The {id} part is a URI template variable. A later chapter explains how @PathVariable binds it. For now, note that the mapping defines the shape of the URL, and the parameter annotation reads the value.
A method with no path, such as @GetMapping alone, answers the class prefix itself:
@GetMapping
public List<Book> search(@RequestParam(required = false) String author,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return service.search(author, page, size);
}This method answers GET /api/books. The query string (?author=...) is not part of the mapping. Spring matches on the path only, and the query string is read afterwards by @RequestParam.
How Spring picks a method
At startup, Spring scans every controller and records each mapping in a registry. For each request, it finds the mappings that match, and if several match, it picks the most specific one. A mapping can constrain more than the path.
- The path pattern must match.
- The HTTP method must match.
- Any
consumes,produces,params, orheadersconditions must match. - If more than one mapping still matches, the more specific one wins.
For paths, a literal segment is more specific than a variable. Consider these two methods in one controller:
@GetMapping("/featured")
public List<Book> featured() {
return service.featured();
}
@GetMapping("/{id}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}A request to /api/books/featured matches both patterns, because featured could be a value for {id}. Spring chooses /featured, since it has no variable. A request to /api/books/42 matches only the second. This is why you do not need to order methods in the file.
If two mappings are equally specific and both match, Spring cannot choose. The application then fails at startup with an IllegalStateException that says "Ambiguous mapping". Because this happens at startup, it is caught quickly.
Narrowing with consumes and produces
consumes limits a mapping by the request's Content-Type header. produces limits it by the request's Accept header, and sets the response Content-Type.
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> create(@RequestBody CreateBookRequest request) {
// body omitted
return ResponseEntity.ok(service.create(request));
}When a request does not satisfy these conditions, Spring answers with an error status instead of a 404:
| Situation | Status |
|---|---|
| Path matches, but not the HTTP method | 405 Method Not Allowed |
| Path and method match, but `Content-Type` is not accepted | 415 Unsupported Media Type |
| Path and method match, but `Accept` cannot be satisfied | 406 Not Acceptable |
| No mapping matches the path | 404 Not Found |
These statuses help when debugging. A 405 means your path is right and your method is wrong. A 415 on a POST usually means the client did not send Content-Type: application/json.
Path patterns
Mapping paths support a small pattern syntax. The most common forms are:
/books/{id}matches one segment and names itid./books/*matches exactly one segment of any value, without naming it./books/**matches zero or more segments. Spring Boot's defaultPathPatternParserallows**only at the end of a pattern./books/{id:[0-9]+}matchesidonly if it satisfies the regular expression.
The regular expression form is a way to separate mappings by shape. Here, numeric values go to one method and anything else to another:
@GetMapping("/{id:[0-9]+}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
@GetMapping("/{slug:[a-z-]+}")
public Book getBySlug(@PathVariable String slug) {
return service.getBySlug(slug);
}A request to /api/books/42 goes to the first method. A request to /api/books/earthsea goes to the second. A value that fits neither, such as /api/books/A1, produces a 404 because no mapping matches.
A related point is that trailing slashes are not matched by default in Spring Framework 6 and later, which Spring Boot 3 uses. /api/books/ does not match a mapping declared as /api/books, so a client that adds a slash gets a 404. Declare the path you expect clients to call, and keep it consistent in documentation.
Returning a response
A handler method can return several kinds of values. Each gives you a different level of control over the response.
| Return type | Effect |
|---|---|
| A domain object or record | Serialized to JSON with status 200 |
| `List<T>` | Serialized to a JSON array with status 200 |
| `ResponseEntity<T>` | You control status, headers, and body |
| `void` with `@ResponseStatus` | No body, with the status you choose |
| `ProblemDetail` | An error body in the standard problem format |
Returning the object directly is the simplest option. Switch to ResponseEntity when you need a specific status or header. For example, a create method returns 201 Created with a Location header, which a later chapter shows in full.
You can also set a fixed status with an annotation:
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
service.delete(id);
}This returns 204 No Content with an empty body once the method finishes without an exception.
A complete controller skeleton
The following class shows the mapping pieces together. It uses a hypothetical BookService and Book record, which you would supply in your project. The method bodies only delegate to the service.
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<Book> list() {
return service.all();
}
@GetMapping("/featured")
public List<Book> featured() {
return service.featured();
}
@GetMapping("/{id:[0-9]+}")
public Book getById(@PathVariable Long id) {
return service.get(id);
}
@DeleteMapping("/{id:[0-9]+}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
service.delete(id);
}
}The resulting routes are:
| Request | Handler |
|---|---|
| `GET /api/books` | `list` |
| `GET /api/books/featured` | `featured` |
| `GET /api/books/42` | `getById` |
| `DELETE /api/books/42` | `delete` |
Common errors
- 404 for a path that looks right. Check the class-level prefix, a trailing slash, and the application's
server.servlet.context-pathproperty, which adds another prefix in front of everything. - Controller not found at all. Spring only scans packages under the class that carries
@SpringBootApplication. A controller in a sibling package is ignored. - Ambiguous mapping at startup. Two methods declare the same path, HTTP method, and conditions. Change one path or add a condition.
- Template error instead of JSON. The class uses
@Controllerwithout@ResponseBody. Switch to@RestController. - 405 on a call that should work. The mapping uses a different HTTP method than the client sent. Compare the two.
Where this leads
The mapping chooses the method. The parameters of that method then receive data from the request. The next chapters take each source in turn: the path with @PathVariable, the query string with @RequestParam, and the body with @RequestBody.
Exercise
A controller declares @GetMapping("/featured") and @GetMapping("/{id}") under the prefix /api/books. A client sends GET /api/books/featured. Which method runs, and why? Then say what happens if the client sends POST /api/books/featured and no POST mapping exists for that path.
Show answer
The /featured method runs. Both patterns match, but Spring prefers the pattern with a literal segment over one with a variable, so the order of methods in the file does not matter. For POST /api/books/featured, the path matches but the HTTP method does not, so Spring answers 405 Method Not Allowed, not 404.
Exercise
Your POST endpoint works in tests but a client gets 415 Unsupported Media Type. The client sends a JSON string in the body. What is the most likely cause, and how do you fix it?
Show answer
The client did not send the header Content-Type: application/json, so the mapping or the @RequestBody converter cannot accept the body. Add that header to the client request. With curl, use -H "Content-Type: application/json".