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:

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

  1. The server reads the request and passes it to the dispatcherHandler bean (Spring's DispatcherServlet). Each request runs in its own Zone, so RequestContextHolder.currentRequest is the request anywhere in its handling, across awaits.
  2. server.context-path is removed from the path. A request outside it is a 404.
  3. The filters run, in @Order (see Filters).
  4. 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).
  5. The router picks a method. Of the mappings whose path pattern matches, it keeps those of the request's HTTP method (405 when none), then those whose consumes suits the Content-Type (415), then those whose produces suits Accept (406), then those whose headers conditions hold (400). The most specific pattern wins, then the mapping with more conditions (see @RequestMapping).
  6. The CORS rules of the method are applied (see CORS).
  7. The interceptors registered by a WebMvcConfigurer run their preHandle (see WebMvcConfigurer).
  8. 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.
  9. 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. A Future is awaited.
  10. The interceptors' postHandle run, then the result is written (see Results).
  11. 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).
  12. Temporary upload files are deleted, and the interceptors' afterCompletion run.

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

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.

See also