Headers, cookies and the request
@RequestHeader() binds a controller parameter to a request header, and @CookieValue() to a cookie. A few types need no annotation at all: the request, the response, its headers, method, URI and user.
Why
Some values travel in headers rather than in the path or the body: a request id, a tenant, an API version, a language, the Last-Event-ID of a reconnecting event stream. Browsers send preferences and session ids as cookies. The annotations read them, convert them and answer a 400 when a required one is missing, as for query parameters.
When a method needs more than one value, it can take the whole request instead.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
@RestController()
@RequestMapping('/api')
class OrderController {
// A required header: a request without X-Request-Id is a 400.
@PostMapping('/orders')
String place(@RequestHeader('X-Request-Id') String requestId) =>
'placed under $requestId';
// Optional headers: null, or the Dart default.
@GetMapping('/orders')
String list({
@RequestHeader('X-Tenant') String tenant = 'public',
@RequestHeader('X-Trace') bool? trace,
}) => 'orders of $tenant${trace == true ? ' (traced)' : ''}';
// Every value of a header: Accept-Language: de, en gives ['de', 'en'].
@GetMapping('/languages')
List<String> languages(@RequestHeader('Accept-Language') List<String> tags) =>
tags;
// All headers, by name without case.
@GetMapping('/agent')
String agent(@RequestHeader() HttpHeaders headers) =>
headers['user-agent'] ?? 'unknown';
// All headers as a plain map; the names as the request sent them.
@GetMapping('/headers')
Map<String, String> headers(@RequestHeader() Map<String, String> all) => all;
// A cookie: Cookie: theme=dark.
@GetMapping('/theme')
String theme({@CookieValue() String theme = 'light'}) => theme;
// The request itself, for what has no annotation.
@GetMapping('/whoami')
String whoami(ServerHttpRequest request, Uri uri, HttpMethod method) =>
'${method.value} ${uri.path} from ${request.remoteAddress} '
'(${request.isSecure ? 'https' : 'http'})';
// The response, to add a header or a cookie before the body is written.
@PostMapping('/login')
String login(ServerHttpResponse response) {
response.headers.set('X-Logged-In', 'yes');
response.addCookie(
ResponseCookie(
'theme',
'dark',
maxAge: const Duration(days: 30),
path: '/',
httpOnly: true,
secure: true,
sameSite: 'Lax',
),
);
return 'welcome';
}
// The user an authentication filter set; none is a 401.
@GetMapping('/me')
String me(Principal user) => user.name;
}
@RequestHeader
| Name | Type | Default | Meaning |
|---|---|---|---|
name (positional) |
String? |
null |
The header name, compared without case. null: the name of the Dart parameter. Not used for an HttpHeaders or Map parameter. |
| Parameter type | Value |
|---|---|
a simple value (String, int, bool, DateTime, an enum, ...) |
the first value of the header, converted as for @RequestParam |
List<T>, Set<T> |
every value of the header; one value with commas is split |
HttpHeaders |
every header, read without case (the same object as without annotation) |
Map<String, String> |
every header, its first value; the keys are the names as sent |
Map<String, List<String>> |
every header with all its values |
@CookieValue
| Name | Type | Default | Meaning |
|---|---|---|---|
name (positional) |
String? |
null |
The cookie name, as in the Cookie header. null: the name of the Dart parameter. |
The value is converted to a simple type as for @RequestParam. To read the session, use request.getSession() rather than the session cookie (see Sessions).
Required or optional
The same rule as for every other value:
| The header or cookie is missing, and the parameter is | Result |
|---|---|
nullable (String? trace) |
null |
optional with a default ({String tenant = 'public'}) |
left out of the call: the Dart default |
| anything else | 400 Required header 'X-Request-Id' is not present., or Required cookie 'theme' is not present. |
A value that does not convert is a 400 that names it: Failed to convert 'X-Trace' with value: 'maybe'.
Parameters without annotation
| Type | Value |
|---|---|
ServerHttpRequest |
the request: method, uri, path (without server.context-path), headers, queryParameters, cookies, remoteAddress, isSecure, attributes, principal, body, contentType, readBodyBytes(), readBodyText(), getSession() |
ServerHttpResponse |
the response: statusCode, headers, addCookie(...), isCommitted, and the body methods add, write, flush, addStream, close |
HttpHeaders |
the request headers |
HttpMethod |
the request method |
Uri |
the request URI, with the query |
Principal |
request.principal, the user an authentication filter set (the security starter sets it). A non-nullable Principal without a user is a 401; a Principal? gets null. |
The match is on the exact type: a subclass of these is not filled this way. Other values come through a HandlerMethodArgumentResolver registered in a WebMvcConfigurer; custom resolvers are asked before the built-in binding, so they can take over any parameter.
Rules for the response:
- Headers and cookies set on the response stay when the method's result is written. The writer sets
Content-TypeandContent-Lengthfor the body; aResponseEntity's headers replace those of the same name. - The status is the result's. Setting
response.statusCodeand then returning a value (or nothing) does not keep it: the result is written with 200, the@ResponseStatusor theResponseEntitystatus. Use those to choose the status. - Writing the body yourself (
response.write(...), thenawait response.close()) and returning nothing works too; once the response is committed, the result is not written again. ResponseCookie(name, value, maxAge:, domain:, path:, secure:, httpOnly:, sameSite:, partitioned:)checks its name and value as RFC 6265 asks: a;,,, space, quote, control or non-ASCII character is anArgumentError. Encode such values first (Uri.encodeComponent).
The request is also reachable outside the controller, anywhere during its handling: RequestContextHolder.currentRequest. Request attributes (request.attributes) carry values from a filter or an interceptor to later code; the starter puts the chosen HandlerMethod under bestMatchingHandlerAttribute and the path variables under uriTemplateVariablesAttribute.
In Spring (Java)
@PostMapping("/api/orders")
String place(@RequestHeader("X-Request-Id") String requestId) { ... }
@GetMapping("/api/orders")
String list(@RequestHeader(name = "X-Tenant", defaultValue = "public") String tenant) { ... }
@GetMapping("/api/theme")
String theme(@CookieValue(name = "theme", defaultValue = "light") String theme) { ... }
@GetMapping("/api/me")
String me(Principal user) { ... }
Differences that matter:
required = falseis a nullable parameter;defaultValueis a Dart default.- The request is a
ServerHttpRequest, not anHttpServletRequest; there is noHttpSessionparameter: callrequest.getSession(). @RequestAttribute,@SessionAttributeand@MatrixVariabledo not exist. Readrequest.attributes, the session, or the raw path.