通过ServletContext可以访问应用范围的初始化参数和属性
1).初始化参数
ServletContext对象是在Web应用程序装载时初始化的。正像Servlet具有初始化参数一样,ServletContext也有初始化参数。Servlet上下文初始化参数指定应用程序范围内的信息。[1]
在web.xml中配置初始化参数:
<context-param>
<param-name>adminEmail</param-name>
<param-value>webmaster</param-value>
</context-param>
<context-param>元素是针对整个应用的,所以并不嵌套在某个<servlet>元素中,该元素是<web-app>元 素的直接子元素。[1]
从Servlet中访问初始化参数:
ServletContext application=this.getServletContext();
out.println("send us your")
out.println(application.getInitParameter("email"));
out.println("'>email");
2).属性
可以通过编程的方式绑定,也可以作为web应用的全局变量被所有Servlet和JSPs访问
设置Context属性:
ServletContext application=this.getServletContext();
application.setAttribute("person1",new Person("Jim"));
application.setAttribute("person2",new Person("Green"));
获取Context属性:
ServletContext application=this.getServletContext();
Enumberation persons=application.getAttributeNames();
while(persons.hasMoreElements()){
String name=(String)persons.nextElement();
Person p=(Person)persons.getAttribute(name);
application.removeAttribute(name);
简单的示例:
package servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 通过 getServletContext()方法获得ServletContext,然后加载配置文件db.properties中的数据
*/
public class ServletContextDemo extends HttpServlet {
//处理方法,doGet()
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//通过相对路径获得绝对路径,然后再交给FileInputStream获得db.properties的流对象
// String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
// InputStream in = new FileInputStream(path);
//直接通过绝对路径获取db.properties的流对象
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
//使用Properties加载配置文件
Properties prop = new Properties();
prop.load(in);
//按名称获取配置文件中的数据
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println("url = "+url);
System.out.println("username = "+username);
System.out.println("password = "+password);
}
//处理方法,doPost()
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml中的配置