SpringMVC笔记- 不配置HandlerMapping

金鞍玉勒寻芳客,未信我庐别有春。这篇文章主要讲述SpringMVC笔记- 不配置HandlerMapping相关的知识,希望能为你提供帮助。
使用SpringMVC框架时发现有的配置了HandlerMapping,而有的没有,那么它们有什么区别呢?不配置能不能正常使用框架呢?
下面我们看一看不配置任何HandlerMapping时,框架会使用什么?
下面我们注释掉框架中配置HandlerMapping的代码

< ?xml version="1.0" encoding="UTF-8"?> 2 < beans xmlns="http://www.springframework.org/schema/beans" 3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 4xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 5xsi:schemaLocation=" 6http://www.springframework.org/schema/beans 7http://www.springframework.org/schema/beans/spring-beans.xsd 8http://www.springframework.org/schema/context 9http://www.springframework.org/schema/context/spring-context.xsd 10http://www.springframework.org/schema/mvc 11http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 12 13< context:component-scan base-package="com.springmvc.demo.controller" /> 14 15< !-- < bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> 16< bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> --> 17< !-- < mvc:default-servlet-handler/> --> 18< !-- < mvc:annotation-driven /> --> 19< !-- < mvc:resources location="/resource/images/" mapping="/images/**" /> --> 20< bean id="/simpleController" class="com.springmvc.demo.controller.SimpleController"> < /bean> 21 22< !-- < bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> 23< /bean> --> 24 25< bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 26< property name="viewClass" value="https://www.songbingjia.com/android/org.springframework.web.servlet.view.JstlView" /> 27< property name="prefix" value="https://www.songbingjia.com/" /> 28< property name="suffix" value="https://www.songbingjia.com/android/.jsp" /> 29< /bean> 30 31 32 < /beans>

这次我们打一断点调试一下看看使用了什么HandlerMapping:
【SpringMVC笔记- 不配置HandlerMapping】 
SpringMVC笔记- 不配置HandlerMapping

文章图片

可以看到注册了两个HandlerMapping,所以:
1.访问/simpleController,正常
2.访问/user/preAddUser(通过@RequestMapping注解的)也正常,因为DefaultAnnotationHandlerMapping也可以处理注解,这个还是spring3.1之前处理注解的一个类,3.1及以后改为了RequestMappingHandlerMapping这个类,查看api可以看到这个类【已经过期】,默认情况继续使用这个类可能是为了向后兼容。
其实这是一个默认配置,位置在spring-webmvc.jar里面,如果你没有显式注册一个HandlerMapping,那么就会使用org.springframework.web.servlet.DispatcherServlet.properties这个里面默认的配置,配置如下:
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\\
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
所以就会注册上面两个RequestMapping。

    推荐阅读