How to configure multiple handlers in a Spring MVC web application


In Spring MVC, DispatcherServlet relies on handler mapping to determine which controller the request should be sent to. All handler mapping classes in Spring implement org.springframework.web.servlet.HandlerMapping interface. Spring distribution contains following four implementation of HandlerMapping interface.

  • BeanNameUrlHandlerMapping
  • SimpleUrlHandlerMapping
  • ControllerClassNameHandlerMappign
  • CommonsPathMapHandlerMapping

BeanNameUrlHandlerMapping is the simplest of all and DispatcherServlet looks for this mapping by default.

You can use any one of these handler mappings in your application by just configuring a bean in your application context file. For e.g; to use BeanNameUrlHandlerMapping you will have a bean declaration similar to



But can you use more than one handler mappings in an application? The answer is yes, you can. The question then arises how does DispatcherServlet know which handler mapping to choose?
Well, you will have to guide Spring by setting the order property of the handler mapping beans. Every handler mapping class implements Ordered interface. So all you have to to is to set order property to indicate the precedence of your handler beans.

DispatcherServlet will consult each one of them in the order according to their priority set by order property. If a HandlerMapping does not return an appropriate HandlerExecutionChain (that is, it returns null), the next available HandlerMapping will be consulted. If no appropriate result is found after inspecting all HandlerMappings an exception will be thrown.

 
    
      
    								 
    
    
    
    
    
    
    
    


In the above example, bean “urlMapping” has the lowest order and hence has the highest priority. This means that the DispatcherServlet will first consult SimpleUrlHandlerMapping when trying to map a URL to a controller. The servlet will consult “beanNameUrlMapping” handler only if the UrlMapping did not return any result.