使用SpringMVC框架时发现有的配置了HandlerMapping,而有的没有,那么它们有什么区别呢?不配置能不能正常使用框架呢?
下面我们看一看不配置任何HandlerMapping时,框架会使用什么?
下面我们注释掉框架中配置HandlerMapping的代码
xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
5 xsi:schemaLocation="
6 http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12
13 <context:component-scan base-package="com.springmvc.demo.controller" />
14
15
17
18
19
20 <bean id="/simpleController" class="com.springmvc.demo.controller.SimpleController">bean>
21
22
24
25 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
26 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
27 <property name="prefix" value="/" />
28 <property name="suffix" value=".jsp" />
29 bean>
30
31
32 beans>
这次我们打一断点调试一下看看使用了什么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。