JSP application 對象用于保存應用程序的公用數據,服務器啟動并自動創建 application 對象后,只要沒有關閉服務器,application 對象就一直存在,所有用戶共享 application 對象。
JSP application 對象是 javax.servlet.ServletContext 類的實例,這有助于查找有關 Servlet 引擎和 Servlet 環境的信息。它的生命周期從服務器啟動到關閉。在此期間,對象將一直存在。這樣,在用戶的前后連接或不同用戶之間的連接中,可以對此對象的同一屬性進行操作。在任何地方 對此對象屬性的操作,都會影響到其他用戶的訪問。
表 1 列出了 application 對象的常用方法。
方法 |
說明 |
---|---|
getAttribute( String arg) |
獲取 application 對象中含有關鍵字的對象 |
getAttributeNames() |
獲取 application 對象的所有參數名字 |
getMajorVersion() |
獲取服務器支持 Servlet 的主版本號 |
getMinorVersion() |
獲取服務器支持 Servlet 的從版本號 |
removeAttribute(java.lang.String name) |
根據名字刪除 application 對象的參數 |
setAttribute(String key,Object obj) |
將參數 Object 指定的對象 obj 添加到 application 對象中,并 為添加的對象指定一個索引關鍵字 |
例1:利用 application 對象查找 Servlet 有關的屬性信息,包括 Servlet 的引擎名、版本號、服務器支持的 Servlet API 的最大和最小版本號、指定資源的路徑等。文件名為 Test.jsp,代碼如下:
<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>application對象查找servlet有關的屬性信息</title>
<head>
<body>
JSP(SERVLET)引擎名及版本號:
<%=application.getServerInfo()%><br>
服務器支持的 Server API 的最大版本號:
<%=application.getMajorVersion ()%><br>
服務器支持的 Server API 的最小版本號:
<%=application.getMinorVersion ()%><br>
指定資源(文件及目錄)的 URL 路徑:
<%=application.getResource("Test.jsp")%><br>
返回 Test.jsp 虛擬路徑的真實路徑:
<%=application.getRealPath("Test.jsp")%>
</body>
</html>
運行結果如圖 1 所示。
圖1 利用application對象查找Servlet有關的屬性信息
管理應用程序屬性
application 對象與 session 對象相同,都可以設置屬性。但是,兩個屬性的有效范圍是不同的。
在 session 對象中,設置的屬性只在當前客戶的會話范圍(session scope)有效,客戶超過預期時間不發送請求時,session 對象將被回收。
在 application 對象中設置的屬性在整個應用程序范圍(application scope)都有效。即使所有的用戶都不發送請求,只要不關閉應用服務器,在其中設置的屬性也是有效的。
例2:以 application 對象管理應用程序屬性。用 application 對象的 setAttribute() 和 getAttribute() 方法實現網頁計數器功能,代碼如下:
<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>application對象實現網頁計數器</title>
<head>
<body>
<%
int n=0;
if(application.getAttribute("num")==null)
n=1;
else
{
String str=application.getAttribute("num").toString();
//getAttribute("num")返回的是Object類型
n=Integer.valueOf(str).intValue()+1;
}
application.setAttribute("num",n);
out.println("您好,您是第"+application.getAttribute("num")+"位訪問客戶!");
%>
</body>
</html>
運行結果如圖 2 所示。
圖2 網站計數器