概要
每個應用都會有一個
ServletContext
對象與之關(guān)聯(lián),當容器分布在多個虛擬機上時,web應用在所分布的每個虛擬機上都擁有一個 ServletContext
實例。缺省情況下, ServletContext
不是分布式的,并且只存在于一個虛擬機上。通過ServletContext可以訪問應用范圍的初始化參數(shù)和屬性:
1).初始化參數(shù)
ServletContext對象是在Web應用程序裝載時初始化的。正像Servlet具有初始化參數(shù)一樣,ServletContext也有初始化參數(shù)。Servlet上下文初始化參數(shù)指定應用程序范圍內(nèi)的信息。
在web.xml中配置初始化參數(shù):
adminEmail
webmaster
元素是針對整個應用的,所以并不嵌套在某個元素中,該元素是元 素的直接子元素。
從Servlet中訪問初始化參數(shù):
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);
用途
安裝方法:
安裝在一個服務器中的一個特定URL名字空間(比如,/myapplication)下的所有Servlet,JSP,JavaBean等Web部件的集合構(gòu)成了一個Web的應用,每一個Web應用(同一JVM),容器都會有一個背景對象,而javax.servlet.ServletContext接口就提供了訪問這個背景對象的途徑。
Servlet實例的getServletContext方法:
得到該Servlet運行其中的這個背景對象。從這個背景對象中你可以訪問如下信息或資源:(注意該方法不是ServletContext的方法而是獲取背景對象的方法由于HttpServlet繼承Servlet的關(guān)系GenericServlet類和HttpServlet類同時具有該方法):初始化參數(shù) ServletContext.getInitParameter(String name)。存儲在背境中的對象 context.getAttribute(String name) 與本背景關(guān)聯(lián)的資源 ServletContext.getResource(String path) 日志 ServletContext.log(String msg) 以上所示方法均為ServletContext所提供,值得一提的是對于存儲在背景中的對象訪問方法常用的還有: context.setAttribute(String name, Object object);將特定名字綁定的任意類型的對象上。將把object對象綁定到名字name,存放在Servlet背景中,可供同一背景中的其他Servlet共享。其他Servlet可以通過context.getAttribute(String name),得到一個背景中的對象,或通過context.removeAttribute(String name)在背景中移除一個對象。
在Web應用范圍內(nèi)存取共享數(shù)據(jù)的方法:
注:web應用范圍具有以下兩層含義:
(1)表示有web應用的生命周期構(gòu)成的時間段.
(2)表示在web應用的生命周期內(nèi)所有web組件的集合。
setAttribute(String name,java.lang.Objectobject):把一個java 對象和一個屬性名綁定,并存放到ServletContext 中,參數(shù)name 指定屬性名,參數(shù)Object 表示共享數(shù)據(jù)。
getAttribute(String name):根據(jù)參數(shù)給定的屬性名,返回一個Object類型的對象。
getAttributeNames():返回一個Enumeration 對象,該對象包含了所有存放在ServletContext 中的屬性名
removeAttribute(String name) :根 據(jù) 參 數(shù) 指 定 的 屬 性 名,從servletContext 對象中刪除匹配的屬性。
getRealPath("/"):得到絕對路徑
訪問web應用的靜態(tài)資源
使用ServletContext接口可以直接訪問web應用中的靜態(tài)內(nèi)容文檔結(jié)構(gòu)。包括HTML,GIF和JPEG文件。如以下方法:
.getResource
.getResourceAsStream
這兩個方法的參數(shù)都是以"/"開頭的字符串,表示資源相對于context根的相對路徑.文檔結(jié)構(gòu)可以存在于服務器文件系統(tǒng),或是war包中,或是在遠程服務器上,抑或其他位置。不可以用來獲得動態(tài)資源,比如,getResource("/index.jsp"),這個方法將返回該jsp文件的源碼,而不是動態(tài)頁面。可以用"Dispatching Requests"獲得動態(tài)內(nèi)容.
列出web應用中可被訪問的資源,可以使用getResourcePaths(String path)方法。
跨多個請求,用戶和Servlets
web服務器支持在一臺機器上共享一個IP的多個邏輯主機,這種能力被稱為"虛擬主機",每個邏輯主機都擁有它自己的servlet context。servlet context不能跨虛擬主機共享。