context-param 为上下文初始化参数

解析:每个<context-param>元素含有一对参数名和参数值(param-name和param-value),用作应用的Servlet上下文初始化参数,

参数名在整个Web应用中必须是惟一的,在web应用的整个生命周期中上下文初始化参数都存在,任意的Servlet和jsp都可以随时随地访问它。

什么时候需要它?

比如:当我们定义一个管理员email地址,用来从程序发送错误,或者与整个应用程序有关的其他设置,使用自定义的设置文件需要额外的代码和管理,

而直接在程序中使用硬编码(Hard-coding)参数值会给你之后修改程序带来麻烦,更困难的是,要根据不同的部署使用不同的设置;

但context-param可作为一个用于设置这种参数的标准位置。

 

常见的例子:

1. 为Spring添加配置文件

Spring配置文件默认的路径是/WEB-INF/applicationContext.xml,即WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。

但通过在web.xml里加入contextConfigLocation,可指定相应的xml文件名,如果有多个xml文件,可以写在一起并以“,”号分隔,例如:

 



<!-- spring config -->  
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-configuration/*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


 

日志的配置,spring之后废弃了这种配置 (不知道是那个版本,大家可以网上搜索下)



<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>


 

我是这样加载了下



<context:property-placeholder location="classpath:jdbc.properties"/>

或者

<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties<value/>
</list>
</property>
</bean>