Handler mappings
A HandlerMapping decides which handler answers a request. The dispatcher asks every HandlerMapping bean in order, and the first one that returns a handler wins. The dispatcherHandlersMappingDescriptions bean lists them all, for the actuator's mappings endpoint.
Why
Most requests are answered by controller methods. But other parts of the application answer requests too: static files, WebSocket endpoints, actuator endpoints. Each of them is a handler mapping, and their order decides who gets a path that several could answer. A controller always wins over a static file of the same path, for example.
You write a handler mapping of your own when no controller fits: paths computed at run time, a proxy for a legacy system, a health check answered without the controller machinery.
Listing the mappings answers the question "which URLs does this application serve, and who answers them?", for people and for tools.
Example
A health check answered without a controller, listed with the other mappings:
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
@Component()
@Order(10)
class HealthMapping implements HandlerMapping, DescribableHandlerMapping {
static final _handler = FunctionHttpHandler(
(request, response) => response.send(200, 'UP'),
);
@override
HttpHandler? getHandler(ServerHttpRequest request) =>
request.path == '/health' ? _handler : null;
@override
List<Map<String, Object?>> describeHandlers() => [
{'predicate': '/health', 'handler': 'HealthMapping'},
];
}
The mappings as the actuator shows them:
management.endpoints.web.exposure.include=health,mappings
GET /actuator/mappings
{"contexts": {"application": {"mappings": {
"dispatcherHandlers": {"webHandler": [
{"predicate": "{GET [/api/books/{isbn}]}",
"handler": "BookController#find(String)",
"details": {
"handlerMethod": {"className": "BookController", "name": "find",
"descriptor": "(String isbn) -> Future<Book>"},
"requestMappingConditions": {"consumes": [], "headers": [], "methods": ["GET"],
"params": [], "patterns": ["/api/books/{isbn}"], "produces": []}}},
{"predicate": "/health", "handler": "HealthMapping"},
{"predicate": "/**", "handler": "ResourceWebHandler [resources:static/, resources:public/]"},
{"predicate": "(GET && /)", "handler": "WelcomePage [index.html]"}]}},
"parentId": null}}}
How a handler is chosen
For every request, the dispatcherHandler bean (Spring's DispatcherServlet):
- removes
server.context-path(a path outside it is a 404); - runs the
WebFilterbeans, in order; - asks each
HandlerMappingbean in turn, sorted by@OrderorOrdered; - calls the first handler returned;
- answers with a 404 when no mapping returned one: a
ProblemDetailwith the detailNo endpoint GET /x..
A mapping may also throw, for example a 405 for a known path with another method. The dispatcher then answers with that error.
The mappings of the starters:
| Bean | Order | Answers |
|---|---|---|
the actuator starter's WebEndpointHandlerMapping |
-100 |
the actuator's endpoints (/actuator/...) |
requestMappingHandlerMapping |
0 |
the @RestController methods |
the WebSocket starter's WebSocketHandlerMapping |
1 |
the WebSocket handshakes |
resourceHandlerMapping |
Ordered.lowestPrecedence - 1 |
the static resources and the welcome page |
A mapping without an order gets Ordered.lowestPrecedence: it is asked last, even after the static resources. Give your mapping an @Order (or implement Ordered) to be asked before them.
Writing a mapping
abstract interface class HandlerMapping {
FutureOr<HttpHandler?> getHandler(ServerHttpRequest request);
}
- Return
nullto let the next mapping try. - Return an
HttpHandler, often aFunctionHttpHandler. The handler must write the whole response;response.send(status, text)does it in one call. - The request has passed the filters already (security, sessions, forwarded headers).
- Errors the handler throws are answered as
ProblemDetails, through the@ExceptionHandlermethods of the controllers and theHandlerExceptionResolverbeans. See Errors. HandlerInterceptors do not run: they are for controller methods.
Listing the mappings
The dispatcherHandlersMappingDescriptions bean
The starter declares a DispatcherHandlersMappingDescriptions bean named dispatcherHandlersMappingDescriptions. It is a MappingDescriptions (from spring_web_dart):
mappingsNameisdispatcherHandlers;describeMappings()returns{'webHandler': [...]}: every handler of every handler mapping of the dispatcher that implementsDescribableHandlerMapping, in the order the mappings are asked.
The shape is Spring WebFlux's dispatcherHandlers. webHandler is Spring's name of the dispatcher.
The actuator's mappings endpoint (spring_boot_starter_actuator) puts every MappingDescriptions bean under its name. With the navigation starter, the app's screens appear next to dispatcherHandlers.
You can read the list in code too, for example in a test:
final mappings = context.getBean<DispatcherHandlersMappingDescriptions>();
final handlers = mappings.describeMappings()['webHandler']! as List<Object?>;
final predicates = [
for (final handler in handlers.cast<Map<String, Object?>>()) handler['predicate'],
];
expect(predicates, contains('/health'));
What each entry holds
| Key | What |
|---|---|
predicate |
what the mapping matches, as Spring's RequestMappingInfo.toString(): {GET [/api/books/{isbn}], produces [application/json]} |
handler |
who answers: BookController#find(String), ResourceWebHandler [resources:static/], WelcomePage [index.html] |
details.handlerMethod |
for a controller method: className, name, and descriptor, the Dart signature ((String isbn) -> Future<Book>). Spring's descriptor is the JVM's. |
details.requestMappingConditions |
methods, patterns, params and headers (each {name, value, negated}), consumes and produces (each {mediaType, negated}) |
The predicate lists only the conditions a mapping has, in Spring's order: the method, the patterns, then params, headers, consumes, produces. Several values are joined with ||.
Describing your own mapping
Implement DescribableHandlerMapping and return one map per handler. For a mapping with method-like conditions, describeRequestMapping builds the map in the same shape as the controllers':
@override
List<Map<String, Object?>> describeHandlers() => [
describeRequestMapping(
handler: 'LegacyProxy',
patterns: ['/legacy/**'],
methods: ['GET', 'POST'],
produces: ['application/xml'],
),
];
// {"predicate": "{[GET, POST] [/legacy/**], produces [application/xml]}", ...}
At startup
The controllers' mapping logs its routes under the logger spring.web.mvc:
logging.level.spring.web.mvc=trace
DEBUG 12 mappings in 'requestMappingHandlerMapping'
TRACE Mapped ...
debug shows the count, trace one line per mapping. Invalid controllers stop the start with the list of problems. See Startup checks.
In Spring (Java)
@Component
class HealthMapping extends AbstractHandlerMapping {
@Override
protected Object getHandlerInternal(HttpServletRequest request) {
return "/health".equals(request.getRequestURI()) ? new HealthHandler() : null;
}
}
Differences that matter:
- A
HandlerMappingreturns anHttpHandlerthat writes the response, not a handler object that aHandlerAdaptercalls. - The actuator's list has Spring WebFlux's shape (
dispatcherHandlers), not Spring MVC's (dispatcherServlets), and the descriptor is the Dart signature. - A mapping is listed only when it implements
DescribableHandlerMapping.