我們都知web項目的運行,通常會首先加載web.xml文件,但卻對web.xml文件知之甚少,今天就來揭開它的面紗,一睹它的真容!
一.web.xml是什么?
web.xml是web項目的配置文件,一般的web工程都會用到web.xml來配置,主要用來配置Listener,Filter,Servlet等。
但需要注意的是:web.xml並不是必須的,一個web工程可以沒有web.xml文件
二.web項目加載web.xml過程
Tomcat啟動web項目時,web容器就會的加載首先加載web.xml文件,
加載過程如下:
1.web項目加載web.xml,讀取context-param和listener這兩個結點,
2.創建一個ServletContext(Servlet上下文),整個項目會共享這個ServletContext
3.容器將<context-param>轉換為鍵值對,並交給ServletContext
4.容器創建<listener>中的類實例,創建監聽器
三.web.xml元素詳解
首先是表明xml的使用版本。
<?xml version="1.0" encoding="UTF-8"?>
web-app是web.xml的根元素,包含着web.xml所有子元素。
xmlns以及xmlns:xsi后面引進的連接是表明web.xml引進的模式文件,便能擁有該模式的相關功能。
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> </web-app>
指明項目名稱
<display-name>web-SSMTest</display-name>
web項目加載web.xml首先讀取這兩個結點,加載spring容器及創建spring監聽器;
ApplicationContext.xml 是spring 全局配置文件,用來控制spring 特性的
ContextLoaderListener的作用就是啟動Web容器時,自動裝配ApplicationContext的配置信息。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
這個過濾器就是針對於每次瀏覽器請求進行過濾的
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
配置DispatcherServlet 前端控制器,加載springMVC容器
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加載的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
展示首頁頁面
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
session配置
<session-config>
<session-timeout>15</session-timeout>
</session-config>
