
# 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](request-mapping.md) and the other mappings;
- where its values come from: [@PathVariable](path-variable.md), [@RequestParam](request-param.md), [@RequestBody](request-body.md), [@RequestHeader and @CookieValue](headers-and-cookies.md);
- how the answer is written: [Results](results.md);
- how errors are answered: [Errors](../errors/index.md).

## Example

```dart
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 `await`s.
2. **`server.context-path`** is removed from the path. A request outside it is a 404.
3. **The filters** run, in `@Order` (see [Filters](../filters.md)).
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](../server/handler-mappings.md)).
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](request-mapping.md)).
6. **The CORS rules** of the method are applied (see [CORS](../cors.md)).
7. **The interceptors** registered by a `WebMvcConfigurer` run their `preHandle` (see [WebMvcConfigurer](../web-mvc-configurer.md)).
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](results.md)).
11. **An exception** at any of steps 5 to 10 goes to the [@ExceptionHandler](../errors/exception-handler.md) methods, then to the [HandlerExceptionResolver](../errors/handler-exception-resolver.md) beans, then to the default answer (see [Errors](../errors/index.md)).
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](path-variable.md) |
| `@RequestParam('q') String query` | a query parameter or a form field; a `Map` takes all | [@RequestParam](request-param.md) |
| `@RequestBody() Book book` | the body, as JSON (or text, bytes, a stream, a form map) | [@RequestBody](request-body.md) |
| `@RequestBody() @Valid() NewBook book` | the body, validated; a violation is a 400 | [@RequestBody](request-body.md) |
| `@RequestHeader('X-Trace') String? trace` | a header; an `HttpHeaders` or a `Map` takes all | [Headers and cookies](headers-and-cookies.md) |
| `@CookieValue('session') String session` | a cookie | [Headers and cookies](headers-and-cookies.md) |
| `@RequestPart('cover') MultipartFile cover` | a part of a multipart upload | [Uploads](../streaming/uploads.md) |
| `ServerHttpRequest`, `ServerHttpResponse`, `HttpHeaders`, `HttpMethod`, `Uri`, `Principal` | the request, the response, its headers, method, URI, user | [Headers and cookies](headers-and-cookies.md) |
| a simple type without annotation (`String q`, `int page`) | the query parameter of that name | [@RequestParam](request-param.md) |
| a type of your own | a `HandlerMethodArgumentResolver` you register | [WebMvcConfigurer](../web-mvc-configurer.md) |

**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](rest-controller.md): the class annotation, the bean, `@ResponseStatus` on the class.
- [@RequestMapping and @GetMapping](request-mapping.md): every mapping annotation and attribute, path patterns, matching order.
- [@PathVariable](path-variable.md): path variables and their conversion.
- [@RequestParam](request-param.md): query parameters, form fields, lists and maps.
- [@RequestBody](request-body.md): JSON, text, bytes, streams and forms; `@Valid()`.
- [Headers, cookies and the request](headers-and-cookies.md): `@RequestHeader`, `@CookieValue` and the parameters without annotation.
- [Results](results.md): every return type, `ResponseEntity`, `@ResponseStatus`, conditional requests.
- [Startup checks](startup-checks.md): what is checked at startup, and the exact messages.

## In Spring (Java)

```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

- [Errors](../errors/index.md)
- [Testing](../testing.md)
- [@Controller in spring_core_dart](../../spring-core-dart/beans/controller.md)
