> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/programming-language/java/spring/springmvc.md).

# SpringMVC

## 基本结构

![图 1](/files/p2X8sOzlwqxLTZwDJZ8P)

1. DispatcherServlet接受所有请求，并负责分发请求信息给对应的Controller处理
2. Controller负责处理对应的请求，完成业务信息，最后返回Model(数据，比如jsp需要渲染的数据、等待进行json序列化的对象)以及View(视图，比如jsp、freemarker、json、xml、文件流)
3. 使用Model渲染View，并将结果返回给浏览器

## 引入相关依赖

```xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
```

## 声明用于分发请求的DispatcherServlet

所有的请求都会被这个Servlet接收，并交由对应的Controller去处理，web.xml如下：

```xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name>Spring Web MVC Demo XML</display-name>

    <!--使用spring-web提供的ContextLoaderListener（ServletContextListener），在初始化servlet容器时，初始化根spring ioc容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--ContextLoaderListener会通过寻找如下参数，确定根容器配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:app-context.xml</param-value>
    </context-param>

    <!--配置DispatcherServlet，在其内部会初始化Spring Mvc子容器，使用contextConfigLocation指定子容器配置文件-->
    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param><!--指定web mvc子容器的配置文件-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:app-mvc-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--DispatcherServlet匹配处理所有以app开头的url链接，并委派组件处理请求-->
    <servlet-mapping>
        <servlet-name>app</servlet-name>
        <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

</web-app>
```

## 定义Controller

## DispatcherServlet如何将请求分发给对应的Controller？
