ヘッダー、クッキー、リクエスト

@RequestHeader() はコントローラーの引数をリクエストヘッダーに、@CookieValue() はクッキーにバインドします。いくつかの型にはアノテーションがまったく要りません。リクエスト、レスポンス、そのヘッダー、メソッド、URI、ユーザーです。

使う理由

パスやボディではなく、ヘッダーで送られる値があります。リクエスト ID、テナント、API のバージョン、言語、再接続するイベントストリームの Last-Event-ID などです。ブラウザーは設定やセッション ID をクッキーで送ります。これらのアノテーションは、クエリパラメーターと同じように値を読み、変換し、必須のものがなければ 400 で応答します。

メソッドが複数の値を必要とする場合は、代わりにリクエスト全体を受け取れます。

例

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

@RestController()
@RequestMapping('/api')
class OrderController {
  // 必須のヘッダー: X-Request-Id のないリクエストは 400。
  @PostMapping('/orders')
  String place(@RequestHeader('X-Request-Id') String requestId) =>
      'placed under $requestId';

  // 省略可能なヘッダー: null、または Dart のデフォルト。
  @GetMapping('/orders')
  String list({
    @RequestHeader('X-Tenant') String tenant = 'public',
    @RequestHeader('X-Trace') bool? trace,
  }) => 'orders of $tenant${trace == true ? ' (traced)' : ''}';

  // ヘッダーのすべての値: Accept-Language: de, en は ['de', 'en']。
  @GetMapping('/languages')
  List<String> languages(@RequestHeader('Accept-Language') List<String> tags) =>
      tags;

  // すべてのヘッダー。名前は大文字小文字を区別しない。
  @GetMapping('/agent')
  String agent(@RequestHeader() HttpHeaders headers) =>
      headers['user-agent'] ?? 'unknown';

  // すべてのヘッダーをプレーンなマップで。名前はリクエストが送ったとおり。
  @GetMapping('/headers')
  Map<String, String> headers(@RequestHeader() Map<String, String> all) => all;

  // クッキー: Cookie: theme=dark。
  @GetMapping('/theme')
  String theme({@CookieValue() String theme = 'light'}) => theme;

  // アノテーションのないもののために、リクエスト自体を受け取る。
  @GetMapping('/whoami')
  String whoami(ServerHttpRequest request, Uri uri, HttpMethod method) =>
      '${method.value} ${uri.path} from ${request.remoteAddress} '
      '(${request.isSecure ? 'https' : 'http'})';

  // ボディが書かれる前にヘッダーやクッキーを追加するために、レスポンスを受け取る。
  @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';
  }

  // 認証フィルターが設定したユーザー。いなければ 401。
  @GetMapping('/me')
  String me(Principal user) => user.name;
}

@RequestHeader

名前 型 デフォルト 意味
name(位置引数) String? null ヘッダー名。大文字小文字を区別せずに比較される。null なら Dart の引数の名前。HttpHeaders や Map の引数では使われない。
引数の型 値
単純な値(String、int、bool、DateTime、enum など) ヘッダーの最初の値。@RequestParam と同じように変換される
List<T>、Set<T> ヘッダーのすべての値。カンマを含む 1 つの値は分割される
HttpHeaders すべてのヘッダー。大文字小文字を区別せずに読める(アノテーションなしと同じオブジェクト)
Map<String, String> すべてのヘッダーの最初の値。キーは送られた名前のまま
Map<String, List<String>> すべてのヘッダーとそのすべての値

@CookieValue

名前 型 デフォルト 意味
name(位置引数) String? null Cookie ヘッダーでのクッキー名。null なら Dart の引数の名前。

値は @RequestParam と同じように単純な型に変換されます。セッションを読むには、セッションクッキーではなく request.getSession() を使ってください(セッション を参照)。

必須か省略可能か

他のすべての値と同じルールです。

ヘッダーまたはクッキーがなく、引数が 結果
nullable(String? trace) null
デフォルト付きの省略可能な引数({String tenant = 'public'}) 呼び出しから省かれる: Dart のデフォルト
それ以外 400 Required header 'X-Request-Id' is not present.、または Required cookie 'theme' is not present.

変換できない値は、それを示す 400 になります: Failed to convert 'X-Trace' with value: 'maybe'。

アノテーションのない引数

型 値
ServerHttpRequest リクエスト: method、uri、path(server.context-path を除く)、headers、queryParameters、cookies、remoteAddress、isSecure、attributes、principal、body、contentType、readBodyBytes()、readBodyText()、getSession()
ServerHttpResponse レスポンス: statusCode、headers、addCookie(...)、isCommitted、ボディのメソッド add、write、flush、addStream、close
HttpHeaders リクエストヘッダー
HttpMethod リクエストのメソッド
Uri クエリを含むリクエストの URI
Principal request.principal。認証フィルターが設定したユーザー(セキュリティスターターが設定する)。ユーザーがいないとき、non-nullable の Principal は 401、Principal? は null を受け取る。

照合は型の完全一致です。これらのサブクラスはこの方法では埋められません。その他の値は、WebMvcConfigurer で登録した HandlerMethodArgumentResolver を通して受け取ります。独自のリゾルバーは組み込みのバインドより先に問い合わせられるため、どの引数でも引き受けられます。

レスポンスのルール:

リクエストは、その処理中であればコントローラーの外のどこからでも RequestContextHolder.currentRequest で参照できます。リクエスト属性(request.attributes)は、フィルターやインターセプターから後のコードに値を運びます。スターターは、選ばれた HandlerMethod を bestMatchingHandlerAttribute に、パス変数を uriTemplateVariablesAttribute に置きます。

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) { ... }

重要な違い:

関連項目