WebMvcConfigurer

A bean that mixes in WebMvcConfigurer adds things to the controllers: interceptors, CORS rules by path, resolvers for parameters of your own types, and more mappings of static resources. Override only the methods you need; the others do nothing.

Why

The starter sets up the controllers with no interceptors, no global CORS rules and only its own argument resolvers. Each application needs a few additions of its own, and they should live in one place, not be repeated in every controller:

Example

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

const log = SpringLog('app.web');

@Configuration()
class WebConfig with WebMvcConfigurer {
  @override
  void addInterceptors(InterceptorRegistry registry) {
    registry
        .addInterceptor(TimingInterceptor())
        .addPathPatterns(['/api/**'])
        .excludePathPatterns(['/api/health']);
    registry.addInterceptor(AdminOnlyInterceptor());
  }

  @override
  void addCorsMappings(CorsRegistry registry) => registry
      .addMapping('/api/**')
      .allowedOrigins(['https://shop.example'])
      .allowedMethods(['GET', 'POST']);

  @override
  void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) =>
      resolvers.add(TenantResolver());

  @override
  void addResourceHandlers(ResourceHandlerRegistry registry) => registry
      .addResourceHandler(['/assets/**'])
      .addResourceLocations(['file:build/web/assets/'])
      .setCacheControl(CacheControl.maxAge(const Duration(days: 365)).immutable());
}

// Logs how long each controller method took.
final class TimingInterceptor with HandlerInterceptor {
  @override
  bool preHandle(
    ServerHttpRequest request,
    ServerHttpResponse response,
    HandlerMethod handler,
  ) {
    request.attributes['start'] = DateTime.now();
    return true;
  }

  @override
  void afterCompletion(
    ServerHttpRequest request,
    ServerHttpResponse response,
    HandlerMethod handler,
    Object? error,
  ) {
    final start = request.attributes['start'] as DateTime;
    log.info('${handler.description} took ${DateTime.now().difference(start)}'
        '${error == null ? '' : ' and failed with ${error.runtimeType}'}');
  }
}

// Methods marked @AdminOnly() answer 403 to anyone but an admin.
class AdminOnly {
  const AdminOnly();
}

final class AdminOnlyInterceptor with HandlerInterceptor {
  @override
  bool preHandle(
    ServerHttpRequest request,
    ServerHttpResponse response,
    HandlerMethod handler,
  ) {
    if (handler.annotation<AdminOnly>() != null &&
        request.headers['X-Role'] != 'admin') {
      throw ResponseStatusException(HttpStatus.forbidden);
    }
    return true;
  }
}

// A `Tenant tenant` parameter gets the tenant of the X-Tenant header.
class Tenant {
  const Tenant(this.id);
  final String id;
}

final class TenantResolver implements HandlerMethodArgumentResolver {
  @override
  bool supportsParameter(MethodParameter parameter) =>
      parameter.type.type == Tenant;

  @override
  Object? resolveArgument(
    MethodParameter parameter,
    ServerHttpRequest request,
    ServerHttpResponse response,
  ) => Tenant(request.headers['X-Tenant'] ?? 'default');
}

@RestController()
@RequestMapping('/api/orders')
class OrderController {
  @GetMapping()
  String list(Tenant tenant) => 'orders of ${tenant.id}';

  @AdminOnly()
  @DeleteMapping('/{id}')
  void delete(@PathVariable() String id) {}
}

WebMvcConfigurer

Method Called with Use it to
addInterceptors(InterceptorRegistry registry) an empty registry add HandlerInterceptors, for all paths or some.
addCorsMappings(CorsRegistry registry) an empty registry add CORS rules by path pattern. See CORS.
addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) an empty list add resolvers for parameters of your own types.
addResourceHandlers(ResourceHandlerRegistry registry) an empty registry add mappings of static resources. See Static resources.

Rules:

Interceptors

A HandlerInterceptor runs around controller methods. Unlike a filter, it runs only for requests mapped to a controller method, after the method is chosen, and it receives that method.

Method When Return Default
FutureOr<bool> preHandle(request, response, HandlerMethod handler) Before the method, after its CORS check. true to go on; false when the interceptor has answered the request itself. true
FutureOr<void> postHandle(request, response, handler, Object? result) After the method returned result (the value of its Future), before the result is written. Headers can still be added. Not called when the method threw. — nothing
FutureOr<void> afterCompletion(request, response, handler, Object? error) When the request is done: after the result was written, or after an exception was answered. error is that exception, even when an @ExceptionHandler answered it; null on success. — nothing

Rules:

InterceptorRegistry and InterceptorRegistration

Member Meaning
registry.addInterceptor(interceptor) Adds the interceptor after those already added, for every path until the registration restricts it. Returns the registration.
registry.registrations The registrations, in order (read-only).
registration.addPathPatterns(List<String> patterns) Restricts the interceptor to paths matching one of the patterns. Repeated calls add patterns.
registration.excludePathPatterns(List<String> patterns) Keeps the interceptor away from paths matching one of the patterns, even when they are included.
registration.appliesTo(String path) Whether the interceptor runs for a path: it matches an included pattern (or none is set) and no excluded one.
registration.interceptor The interceptor.

Patterns are path patterns (/api/**, /books/{isbn}), matched against the request path without the context path.

HandlerMethod

What an interceptor learns about the method:

Member Meaning
beanName The controller bean's name (orderController).
beanTypeName The controller class's name.
description OrderController.delete, as logs show it.
method The generator's description of the method: name, parameters, annotations, return type.
classAnnotations The annotations on the controller class.
parameters The method's parameters as MethodParameters.
annotation<A>() The annotation of type A on the method, else on the class; null when neither has one.
resolveBean() The controller object the method is called on.

The chosen handler is also in the request attribute bestMatchingHandlerAttribute, and the path variables in uriTemplateVariablesAttribute (a Map<String, String>), for a filter that runs on the way out.

Argument resolvers

A HandlerMethodArgumentResolver supplies parameters the starter does not know how to fill: the current tenant, the current user, a value computed from several headers.

Method When Meaning
bool supportsParameter(MethodParameter parameter) Once per parameter of every controller method, at startup. Whether this resolver fills the parameter.
FutureOr<Object?> resolveArgument(MethodParameter parameter, ServerHttpRequest request, ServerHttpResponse response) Once per request, for each parameter it supports. The value. May return a Future. An exception becomes the request's answer: throw a ResponseStatusException for a 400 or 401.

Rules:

MethodParameter

Member Meaning
name The parameter's name in the source.
type The declared type: type.type is the Dart Type, type.nullable whether null is accepted.
annotations The annotations on the parameter.
annotation<A>() The first annotation of type A, or null. Use it to read the annotation's values.
has<A>() Whether the parameter has an annotation of type A.
index The position among all parameters, positional first, then named.
handler The HandlerMethod it belongs to.
parameter The generator's description, with whether it is named and required.
// A parameter marked @CurrentUser() gets the logged-in user's name; a
// request without one is a 401.
class CurrentUser {
  const CurrentUser();
}

final class CurrentUserResolver implements HandlerMethodArgumentResolver {
  @override
  bool supportsParameter(MethodParameter parameter) => parameter.has<CurrentUser>();

  @override
  Object? resolveArgument(parameter, request, response) =>
      request.principal?.name ??
      (parameter.type.nullable
          ? null
          : throw ResponseStatusException(HttpStatus.unauthorized));
}

CORS mappings

addCorsMappings adds global CORS rules by path pattern. What a mapping leaves out gets permissive defaults: every origin, GET, HEAD and POST, every header, 30 minutes of pre-flight cache. The rules combine with each handler's @CrossOrigin, and they apply to the static resources too. Every rule and edge case: CORS.

Resource handlers

addResourceHandlers adds mappings of static resources with their own patterns, locations and caching. A mapping with the same pattern as spring.mvc.static-path-pattern replaces the default one. Every option: Static resources.

In Spring (Java)

@Configuration
class WebConfig implements WebMvcConfigurer {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new TimingInterceptor())
        .addPathPatterns("/api/**")
        .excludePathPatterns("/api/health");
  }

  @Override
  public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    resolvers.add(new TenantResolver());
  }
}

Differences that matter:

See also