<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringMVC04</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>contextConfigLocationValue></param-value>
</context-param>
作用:该元素用来声明应用范围(整个WEB项目)内的上下文初始化参数。param-name
设定上下文的参数名称。必须是唯一名称param-value
设定的参数名称的值
初始化过程:
在启动Web项目时,容器(比如Tomcat)会读web.xml
配置文件中的两个节点<listener>
和<contex-param>
。
接着容器会创建一个ServletContext
(上下文),应用范围内即整个WEB项目都能使用这个上下文。
接着容器会将读取到<context-param>
转化为键值对,并交给ServletContext
。
容器创建<listener></listener>
中的类实例,即创建监听(备注:listener定义的类可以是自定义的类但必须需要继承ServletContextListener
)。
在监听的类中会有一个contextInitialized(ServletContextEvent event)
初始化方法,在这个方法中可以通过event.getServletContext().getInitParameter("contextConfigLocation")
来得到context-param
设定的值。在这个类中还必须有一个contextDestroyed(ServletContextEvent event)
销毁方法.用于关闭应用前释放资源,比如说数据库连接的关闭。
得到这个context-param
的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早。
由上面的初始化过程可知容器对于web.xml的加载过程是context-param >> listener >> fileter >> servlet**
如何使用
页面中${initParam.contextConfigLocation}
Servlet中String paramValue=getServletContext().getInitParameter("contextConfigLocation")
**