简介:
每个应用都会有一个ServletContext对象与之关联,当容器分布在在多个虚拟机上时,web应用在所分布的每个虚拟机上都拥有一个ServletContext实例.缺省情况下,ServletContext不是分布式的,并且只存在于一个虚拟机上。
通过ServletContext可以访问应用范围的初始化参数和属性。
ServletContext | getContext(String uripath) |
getInitParameter(String name) | |
void | |
getAttribute(String name) | |
RequestDispatcher | getRequestDispatcher(String path) |
getRealPath(String path) | |
RequestDispatcher | getRequestDispatcher(String path) |
getResourcePaths(String path) |
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);
在Web应用范围内存取共享数据的方法:
setAttribute(String name,java.lang.Objectobject):把一个java 对象和一个属性名绑定,并存放到ServletContext 中,参数name 指定属性名,参数Object 表示共享数据。
getAttribute(String name):根据参数给定的属性名,返回一个Object类型的对象。
getAttributeNames():返回一个Enumeration 对象,该对象包含了所有存放在ServletContext 中的属性名
removeAttribute(String name) : 根 据 参 数 指 定 的 属 性 名 , 从servletContext 对象中删除匹配的属性。
getRealPath("/"):得到绝对路径
实例:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//此时:test 工程
ServletContext ctx = this.getServletContext();
String ProjectPath = ctx.getRealPath("");
String INFPath = ctx.getRealPath("/WEB-INF/");
PrintWriter ou = response.getWriter();
ou.println(ProjectPath); //输出:D:\apache-tomcat-7.0.42\webapps\test
ou.println(INFPath);//输出:D:\apache-tomcat-7.0.42\webapps\test\WEB-INF
}
举个实例:读配置文件:
ServletContext ctx = this.getServletContext();
String INFPath = ctx.getRealPath("/WEB-INF/");
LicenseSysConst.webInfPath = INFPath;
PropertyConfigurator.configure(LicenseSysConst.webInfPath + "/log4j.properties");
LicenseSysConst.propsPath = LicenseSysConst.webInfPath + "/cfg.properties";