web.xml中<context-param>与<init-param>的区别在于<context-param>设置的是一个在应用中全局(ServletContext范围内)可见的参数,而<init-param>设置的是一个在应用中局部(ServletRequest范围内)可见的参数。
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>testdemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>appversion</param-name>
<param-value>1.0</param-value>
</context-param>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>yedward</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 5222793251610509039L;
@Override
public void init() throws ServletException {
System.out.println(this.getInitParameter("name"));
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse resposne)
throws ServletException, IOException {
System.out.println(this.getInitParameter("name"));
System.out.println(this.getServletContext().getInitParameter("appversion"));
System.out.println(request.getServletContext().getInitParameter("appversion"));
}
}
上面代码的输出结果是:
yedward
yedward
1.0
1.0
启动一个WEB项目的时候,容器(如:Tomcat)会去配置文件web.xml读两个节点:<listener></listener>和<context-param></context-param>,容器创建一个ServletContext,这个WEB项目所有部分都将共享这个上下文,容器将<context-param></context-param>转化为键值对,并交给ServletContext;容器创建<listener></listener>中的类实例,即创建监听,在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得:
ServletContext = ServletContextEvent.getServletContext();
context-param的值 = ServletContext.getInitParameter("context-param的键");
得到这个context-param的值之后,你就可以做一些操作了。注意,这个时候你的WEB项目还没有完全启动完成,这个动作会比所有的Servlet都要早。换句话说,这个时候,对<context-param>中的键值做的操作,将在WEB项目完全启动之前被执行。