Video in progress
What patterns is Spring MVC's `DispatcherServlet` built on, and where does knowing that help you?
DispatcherServlet is a front controller: every request comes in through one place. Inside, finding the handler (HandlerMapping), invoking it (HandlerAdapter), and converting arguments and the response (resolvers, HttpMessageConverter) are swappable strategies. You extend Spring MVC through exactly those points.
📖 Answer
A request travels roughly like this:
HandlerMappingfinds the handler by URL and method. There are several mappings and they are asked in order, which is a list of strategies.- Along with the handler comes a chain of
HandlerInterceptors (HandlerExecutionChain). DispatcherServletdoesn't know the handler's type. It could be a@Controllermethod, anHttpRequestHandler, or the oldControllerinterface. Each kind has its ownHandlerAdapter, which is the classic adapter: it fits handlers of different shapes to a singlehandle()call.- The parameters of a
@RequestMappingmethod are filled in byHandlerMethodArgumentResolvers, and anHttpMessageConverterturns the response into JSON. If an exception is thrown, theHandlerExceptionResolvers try one after another.
What is this good for? You don't see it every day, but when you need to extend something, these are the points you plug into:
@Configuration
class WebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new CurrentTenantResolver()); // a `Tenant tenant` parameter on a method is filled in automatically
}
}
It helps with debugging too: "404, but the controller exists" is a HandlerMapping problem; "415 Unsupported Media Type" is the converter layer; "the parameter came in as null" is the resolver layer. If you know which layer to look in, you find the problem much faster.
Sign up to mark studied questions and save your progress.