要想理解SpringMVC的配置,首先要理解SpringMVC处理请求的原理:
1️⃣请求离开浏览器之后,第一站会来到DispatcherServlet,然后DispatcherServlet会查询一个或多个处理器映射,然后根据映射将请求任务发送给SpringMVC的控制器(通常用注解@Controller标识的类)。
2️⃣控制器处理完成之后,会有需要返回给用户的信息,这些信息称为模型,控制器要的最后一件事是将模型数据打包,并标出用于渲染输出的视图名,接下来控制器会将模型和逻辑视图名发送回DispatcherServlet(这样控制器就不会和特定的视图相耦合)。
3️⃣DispatcherServlet会使用视图解析器(view resolver)将逻辑视图名匹配为一个特定的视图实现(jsp或其他);
4️⃣视图将模型数据渲染输出,这个输出会通过响应对象传递给客户端。
SpringMVC通常会用到两个应用上下文,DispatcherServlet和ContextLoaderListener:
DispatcherServlet加载包含web组件的bean:处理器映射、控制器、视图解析器;
ContextLoaderListener负责加载应用中其他bean:这些bean通常是驱动后端的中间层和数据层组件。
配置SpringMVC有三种方式: Java配置(不使用web.xml)、XML配置(web.xml读取基于xml的配置方案)、通过xml和Java混合配置(web.xml读取基于java的配置方案)
完整的配置在github上:
https://github.com/hefrankeleyn/learning-area/tree/master/006Spring/springmvc-conf-java
https://github.com/hefrankeleyn/learning-area/tree/master/006Spring/springmvc-conf-xml
https://github.com/hefrankeleyn/learning-area/tree/master/006Spring/springmvc-conf-xml-java
首先引入maven:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.3.18.RELEASE</spring.version>
<aspectj.version>1.9.2</aspectj.version>
<javaee-api.version>7.0</javaee-api.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring 的核心容器: Beans、Core、 Context、 Expression、 Context support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</a