Thursday, September 13, 2012

How to configure multiple handler mappings in Spring MVC

DispatcherServlet is Spring MVC's implementation of the front controller pattern. Essentially, it's a servlet that takes the incoming request, and delegates processing of that request to one of a number of handlers, to determine which controller the request should be sent. When the client request reaches the Dispatcher Servlet, the Dispatcher Servlet tries to find the appropriate Handler Mapping object to map the request.
Spring distribution contains the following Handler mappings


All of the above can be found at org.springframework.web.servlet package. You can use any one of these handler mappings in your application by just configuring it in the application context file. If no handler have been configured, by default BeanNameUrlHandlerMapping will be used. And also you can configure more than one handlers in your application. In case of multiple handlers, we have to guide our DispatcherServlet by setting the order property of the handler mappings. Every handler mapping implements Ordered interface. So all we have to do is set the order
property, where the lower order value has the higher property.

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<prop key="/edit/hello.htm">helloController</prop>
<prop key="/hello.htm">helloController</prop>
<property name="interceptors">
<ref bean="myinterceptor" />
<property name="order" value="0"/>

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="1"/>

<bean name="/adddealer.htm" class="com.practice.web.AddDealerFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="dealer"/>
<property name="commandClass" value="com.practice.domain.Dealer"/>
<property name="successView" value="hello.htm"/>
<property name="dealerManager" ref="dealerManager"/>

In the above example, we have configured 2 handler mappings BeanNameUrlHandlerMapping the default one and the simplest one to, and SimpleUrlHandlerMapping, and set the priority order. So the DispatcherServlet will consult each one of the them in the order according to their priority set by
the order priority. If a HandlerMapping does not return an appropriate HandlerExecutionChain , the next available HandlerMapping will be consulted. If no appropriate result is found after inspecting all HandlerMappings an exception will be thrown.

Happy Programming !!!

No comments:

Post a Comment