handlerMapping的工作就是为每个请求找到合适的处理器handler.
最常用的两个handlerMapping:
BeanNameUrlHandlerMapping: 查找spring容器中和请求的url同名的bean.这个映射器不需要配置,因为spring在找不到handlerMapping的情况下会使用BeanNameUrlHandlerMapping.如果一定要配置,像下面这样就行了:
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
比如有一个请求/index.htm, 则就会找到一个名叫/index.htm的bean来处理这个请求; 这种做法让我们可以做出虚拟目录的效果:
<bean name="/user/index.htm" class="controller.TestController" />
<bean name="/admin/index.htm" class="controller.TestController" />
SimpleUrlHandlerMapping: 这个handlerMapping可以配置请求的url和handler的映射关系.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/project.htm">projectController</prop>
<prop key="/manage.htm">managementController</prop>
<prop key="/user.htm">userController</prop>
<prop key="/upload.htm">fileUploadController</prop>
</props>
</property>
</bean>
前面提到了DiapatcherServlet查询handlerMapping获得handler,handlerMapping事实上返回的是HandlerExecutionChain,HandlerExecutionChain里面的interceptor正是在handlerMapping中配置的:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
<ref bean="someOtherCheckInterceptor"/>
</list>
</property>
<property name="mappings">
<props>
<prop key="/project.htm">projectController</prop>
<prop key="/manage.htm">managementController</prop>
<prop key="/user.htm">userController</prop>
<prop key="/upload.htm">fileUploadController</prop>
</props>
</property>
</bean>