Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a Controller and which is HandlerMapping in Spring MVC?

I am using this link to study Spring MVC. As described dispatcher-servlet is at the top handling all incoming requests.

It also describes that there is a HandlerMapping and a Controller. However, in the source code, only Controller is used. Which is HandlerMapping then? Is is not a separate file?

Or is it present in some other complex scenario?

like image 505
whitehat Avatar asked Dec 27 '11 09:12

whitehat


3 Answers

Controller and HandlerMapping are two different things in Spring MVC. Controller is an actual java class which is used to process the request. We declare @Controller at the top of the class definition. Where as HandlerMapping is build in class of Spring framework. There are many hanlder mappings in Spring framework like BeanNameUrlHandlerMapping, ControllerClassNameHandlerMapping etc. By default, BeanNameUrlHandlerMapping is used to map the request. This class searched in all controller classed to map the particular request with the method.

like image 200
Amit Avatar answered Nov 15 '22 12:11

Amit


When no handler mapping is explicitly specified in configuation, BeanNameUrlHandlerMapping is created and used by default.

From the article you linked:

"By default the DispatcherServlet uses the BeanNameUrlHandlerMapping to map the incoming request. The BeanNameUrlHandlerMapping uses the bean name as the URL pattern. Since BeanNameUrlHandlerMapping is used by default, you need not do any seperate configuration for this."

like image 21
socha23 Avatar answered Nov 15 '22 11:11

socha23


Handler Mapping works as helper for Dispatcher servlet. It helps to identify appropriate controller bean to Dispatcher servlet. Default handler mapping bean is DefaultUrlHandlerMapping.

It identifies controller bean by url. It matches the name in URL with controller bean. If it matches it will return back it to DispatcherServlet and finally the servlet executes the business method of controller and returns ModelAndView object back to dispatcher servlet.

like image 30
mukund shelke Avatar answered Nov 15 '22 10:11

mukund shelke