Controllers
A controller is a bean whose methods answer HTTP requests. Each method carries a mapping annotation, each parameter says where its value comes from, and the return value becomes the response.
Why
The controller holds only the code that is specific to an endpoint: which service to call, with which values. Everything around it is done by the starter and declared with annotations:
- which requests the method answers: @GetMapping and the other mappings;
- where its values come from: @PathVariable, @RequestParam, @RequestBody, @RequestHeader and @CookieValue;
- how the answer is written: Results;
- how errors are answered: Errors.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
enum Genre { fiction, science, poetry }
class Book {
const Book({required this.isbn, required this.title, this.genre = Genre.fiction});
final String isbn;
final String title;
final Genre genre;
}
@Service()
class BookService {
Future<Book> find(String isbn) async => Book(isbn: isbn, title: 'Dune');
Future<List<Book>> search(String query, {int page = 0, Genre? genre}) async =>
[Book(isbn: '978-0', title: query)];
Future<void> delete(String isbn) async {}
}
@RestController()
@RequestMapping('/api/books')
class BookController {
BookController(this.books); // injected like any bean
final BookService books;
// GET /api/books/978-0 → the book as JSON
@GetMapping('/{isbn}')
Future<Book> find(@PathVariable() String isbn) => books.find(isbn);
// GET /api/books?q=dune&page=2&genre=science
@GetMapping()
Future<List<Book>> search(
@RequestParam('q') String query, {
@RequestParam() int page = 0, // missing: the Dart default
@RequestParam() Genre? genre, // missing: null
}) => books.search(query, page: page, genre: genre);
// DELETE /api/books/978-0 → 204 No Content
@DeleteMapping('/{isbn}')
@ResponseStatus(HttpStatus.noContent)
Future<void> delete(@PathVariable() String isbn) => books.delete(isbn);
}
The way of a request
- The server reads the request and passes it to the
dispatcherHandlerbean (Spring'sDispatcherServlet). Each request runs in its ownZone, soRequestContextHolder.currentRequestis the request anywhere in its handling, acrossawaits. server.context-pathis removed from the path. A request outside it is a 404.- The filters run, in
@Order(see Filters). - The handler mappings are asked in order. The controllers come first (
requestMappingHandlerMapping, order 0), then the WebSocket endpoints, then the static resources (see Handler mappings). - The router picks a method. Of the mappings whose path pattern matches, it keeps those of the request's HTTP method (
405when none), then those whoseconsumessuits theContent-Type(415), then those whoseproducessuitsAccept(406), then those whoseheadersconditions hold (400). The most specific pattern wins, then the mapping with more conditions (see @RequestMapping). - The CORS rules of the method are applied (see CORS).
- The interceptors registered by a
WebMvcConfigurerrun theirpreHandle(see WebMvcConfigurer). - The parameters are filled, one by one, from the request. A missing required value is a 400; a value that does not convert is a 400 that names the parameter.
- The method is called on the bean as the container holds it, so AOP advice on the controller (
@Cacheable, method validation, the security starter's@PreAuthorize) applies. AFutureis awaited. - The interceptors'
postHandlerun, then the result is written (see Results). - An exception at any of steps 5 to 10 goes to the @ExceptionHandler methods, then to the HandlerExceptionResolver beans, then to the default answer (see Errors).
- Temporary upload files are deleted, and the interceptors'
afterCompletionrun.
HEAD is answered by every GET mapping (the headers and Content-Length, no body). An OPTIONS request to a mapped path without an OPTIONS mapping gets a 200 with an Allow header.
Parameters at a glance
| Parameter | Value | Page |
|---|---|---|
@PathVariable() String isbn |
{isbn} of the path |
@PathVariable |
@RequestParam('q') String query |
a query parameter or a form field; a Map takes all |
@RequestParam |
@RequestBody() Book book |
the body, as JSON (or text, bytes, a stream, a form map) | @RequestBody |
@RequestBody() @Valid() NewBook book |
the body, validated; a violation is a 400 | @RequestBody |
@RequestHeader('X-Trace') String? trace |
a header; an HttpHeaders or a Map takes all |
Headers and cookies |
@CookieValue('session') String session |
a cookie | Headers and cookies |
@RequestPart('cover') MultipartFile cover |
a part of a multipart upload | Uploads |
ServerHttpRequest, ServerHttpResponse, HttpHeaders, HttpMethod, Uri, Principal |
the request, the response, its headers, method, URI, user | Headers and cookies |
a simple type without annotation (String q, int page) |
the query parameter of that name | @RequestParam |
| a type of your own | a HandlerMethodArgumentResolver you register |
WebMvcConfigurer |
Simple values are String, int, double, num, bool, BigInt, DateTime, Duration, Uri, enums, Object and dynamic, and List or Set of them. A text that does not convert is a 400.
Required or optional comes from the Dart parameter, for every kind of value:
| The request has no value, and the parameter is | Result |
|---|---|
nullable (String? q) |
null |
optional with a default ({int page = 0}, [int page = 0]) |
left out of the call, so the Dart default applies |
| anything else | 400 Required parameter 'q' is not present. |
Pages
- @RestController: the class annotation, the bean,
@ResponseStatuson the class. - @RequestMapping and @GetMapping: every mapping annotation and attribute, path patterns, matching order.
- @PathVariable: path variables and their conversion.
- @RequestParam: query parameters, form fields, lists and maps.
- @RequestBody: JSON, text, bytes, streams and forms;
@Valid(). - Headers, cookies and the request:
@RequestHeader,@CookieValueand the parameters without annotation. - Results: every return type,
ResponseEntity,@ResponseStatus, conditional requests. - Startup checks: what is checked at startup, and the exact messages.
In Spring (Java)
@RestController
@RequestMapping("/api/books")
class BookController {
@GetMapping("/{isbn}")
Book find(@PathVariable String isbn) { ... }
@GetMapping
List<Book> search(@RequestParam("q") String query,
@RequestParam(defaultValue = "0") int page,
@RequestParam(required = false) Genre genre) { ... }
}
The model is Spring MVC's. The differences: the routes are generated at build time, required and default values come from the Dart parameter, there are no views (@Controller writes its result as the body too), and more mistakes are found at startup.