首先,所建立的程序是一个web程序,所以在web.xml文件中进行如下的配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<!
DOCTYPE
web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<
web-app
>
<
display-name
>Archetype Created Web Application</
display-name
>
<!--下面的代码将context-param写在外部,
一般用于加载除Web层的Bean(如DAO、Service等),以便于与其他任何Web框架集成。
-->
<
context-param
>
<
param-name
>contextConfigLocation</
param-name
>
<
param-value
>classpath:applicationContext.xml</
param-value
>
</
context-param
>
<
listener
>
<
listener-class
>org.springframework.web.context.ContextLoaderListener</
listener-class
>
</
listener
>
<!--默认加载DispatcherServlet这个类-->
<
servlet
>
<
servlet-name
>dispatcheServlet</
servlet-name
>
<
servlet-class
>org.springframework.web.servlet.DispatcherServlet</
servlet-class
>
<
init-param
>
<!--
配置DispatcherServlet的一个初始化参数:配置SpringMvc配置文件的位置和名称
实际上也可以不配置,使用默认的位置和名称,默认的配置文件是/WEB-INF/<servlet-name-servlet>.xml
-->
<
param-name
>contextConfigLocation</
param-name
>
<
param-value
>classpath:applicationContext-mvc.xml</
param-value
>
</
init-param
>
<!--当servlet启动时,该servlet也启动-->
<
load-on-startup
>1</
load-on-startup
>
</
servlet
>
<
servlet-mapping
>
<
servlet-name
>dispatcheServlet</
servlet-name
>
<
url-pattern
>/</
url-pattern
>
</
servlet-mapping
>
</
web-app
>
|
项目的目录结构如下:
有了上面的配置代码,那么当web容器启动的时候,会初始化IOC容器,将IOC容器中的bean进行实例化。
DispatcheServlet这个类主要是为了将请求分发给各个@Controller注解标记的类,其工作流程如下: