Sub topic 2
Controllers and Request Mappings
This chapter assumes you have a Spring Boot project with spring-boot-starter-web that starts, and that you know HTTP methods and status codes. Later chapters cover reading data from the request. Here you learn how a request reaches a Java method at all.
What a controller is
A controller is a Spring bean whose methods handle HTTP requests. Mark the class with @RestController. This combines @Controller and @ResponseBody. Spring turns each return value into the response body, and Jackson writes objects as JSON.
Spring finds the controller by component scanning. Put it in the same package as your @SpringBootApplication class, or in a sub-package of it.
How a request finds its method
Spring's DispatcherServlet receives every request. It asks the handler mappings which method matches the HTTP method and path. It calls that method, then converts the return value into the response.
Mapping annotations
@RequestMapping is the general annotation. It accepts a path, an HTTP method, and other conditions. The shortcut annotations fix the HTTP method for you.
| Annotation | Same as | Typical use |
|---|---|---|
| `@GetMapping` | `@RequestMapping(method = GET)` | Read data |
| `@PostMapping` | `@RequestMapping(method = POST)` | Create a resource |
| `@PutMapping` | `@RequestMapping(method = PUT)` | Replace a resource |
| `@PatchMapping` | `@RequestMapping(method = PATCH)` | Partially update |
| `@DeleteMapping` | `@RequestMapping(method = DELETE)` | Remove a resource |
Put @RequestMapping on the class to set a shared prefix. The path on each method is appended to it.
A first controller
This controller is complete. It has no service layer yet.
package com.example.library;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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 {
public record Book(long id, String title) {}
@GetMapping
public List<Book> list() {
return List.of(new Book(1, "A Wizard of Earthsea"));
}
@GetMapping("/featured")
public Book featured() {
return new Book(2, "The Dispossessed");
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Book create() {
return new Book(3, "Placeholder");
}
}The class-level prefix and the method paths combine like this:
GET /api/booksrunslist().GET /api/books/featuredrunsfeatured().POST /api/booksrunscreate()and returns201 Created.
Without @ResponseStatus, a successful method returns 200 OK. This create() ignores the request body. The chapter on @RequestBody fixes that.
Narrowing a mapping
A mapping can also match on content type. The consumes attribute matches the request's Content-Type header. The produces attribute matches the client's Accept header.
@PostMapping(consumes = "application/json", produces = "application/json")
public Book createFromJson() {
return new Book(4, "From JSON");
}Add this method to BookController as an alternative to create(). Do not keep both, because they map the same method and path.
What the errors mean
Mapping problems produce specific status codes. Knowing them saves debugging time.
404 Not Found: no mapping matches the path.405 Method Not Allowed: the path matches, but not for this HTTP method.415 Unsupported Media Type: the requestContent-Typedoes not satisfyconsumes.406 Not Acceptable: theAcceptheader cannot be satisfied byproduces.
Try the first two endpoints with curl:
curl http://localhost:8080/api/books
curl http://localhost:8080/api/books/featured
curl -i -X DELETE http://localhost:8080/api/booksThe last call returns 405, because no method handles DELETE on that path.
Exercise
A controller has @RequestMapping("/api/books") on the class and @GetMapping("/featured") on a method. Which request runs the method, and what status does Spring return for POST /api/books/featured?
Show answer
GET /api/books/featured runs the method. POST /api/books/featured returns 405 Method Not Allowed, because the path matches but no handler accepts POST there.