3

How does the DispatcherServlet (or any other bean, supporting Spring MVC infrastructure), dynamically, resolve the signature of the handler method of the @Component instance, and how does it know, what parameters/types are expected, in which order, in that method?

If I have a "@RequestMapping-ed" handler method, in my @Controller instance, defining any version of its signature:

public String f() {...}

public String f(Model model) {...}

public String f(HttpServletRequest, Model model) {...}

public String f(Model model, HttpServletRequest) {...}

public String f(SomeEntity se, Model model, HttpServletRequest, AnotherModel am) {...}

//so on..

would work fine, disregarding of parameter number, types, and order, which, eventually, are supplied with corresponding arguments, again - disregarding of their number, order and types.

There should be quite a work going underneath, to correctly instantiate expected arguments, pass them in a proper order, maybe even do some type-casting, if needed.. an so on, but I don't grasp the fundamentals of this.

I looked up the corresponding sources from spring-webmvc module, and sources of the DispatcherServlet; however, haven't got a firm grasp of the underlying mechanism.

I can guess, that some BeanPostProcessors could be involved.. doing reflective accesses, and so on.. but even in this case, as I'm not certain on what's happening, I would very much appreciate any valuable input.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66

2 Answers2

0

In Spring MVC there are three implementations of HandlerMapping: BeanNameUrlHandlerMapping, SimpleUrlHandlerMapping and ControllerClassNameHandlerMapping. You can read more about this subject here: https://www.baeldung.com/spring-handler-mappings

0

I've not used Spring in years, but this post gives a pretty good step-by-step outline of the spring mvc request lifecycle

When the DispatcherServlet receives a request, it iterates over this list until it finds a matching handler object for the request in question. For simplicity, let's consider only RequestMappingHandlerMapping.

A bean of this type stores a mapping of @RequestMapping annotated methods (the actual Method object retrieved with reflection) stored as a HandlerMethod instances and wrapped in RequestMappingInfo objects that hold mapping data for matching the request, ie. URL, headers, and request parameters.

The DispatcherServlet retrieves the best matching HandlerMethod from these and any corresponding HandlerInterceptor instances which you may have registered. It retrieves these as a HandlerExecutionChain object. It will first apply any pre-handling by HandlerInterceptors. It will then try to invoke your HandlerMethod. This will typically (but not always) be a @RequestMapping annotated method inside a @Controller annotated class. This produces what Spring calls a dispatch result. The DispatcherServlet then applies post-handling by the HandlerInterceptors.