JSP 的內置對象還包括 pageContext、page、config,在接下來的教程中我們將介紹這些內置對象的語法與應用。
pageContext 是頁面上下文對象,這個特殊的對象提供了 JSP 程序執行時所需要用到的所有屬性和方法,如 session、application、config、out 等對象的屬性,也就是說,它可以訪問本頁所有的 session,也可以取本頁所在的 application 的某一屬性值,它相當于頁面中所有其他對象功能的集大成者,可以用它訪問本頁中所有的其他對象。
pageContext 對象是 javax.servlet:jsp.pageContext 類的一個實例,它的創建和初始化都是由容器來完成的,JSP 頁面里可以直接使用 pageContext 對象的句柄,pageContext 對象的 getXxx()、setXxx() 和 findXxx() 方法可以根據不同的對象范圍實現對這些對象的管理。表 1 列出了 pageContext 對象的常用方法。
表1 pageContext對象的常用方法
方法 |
說明 |
---|---|
void forward(String relativeUrlPath) |
把頁面轉發到另一個頁面或者 Servlet 組件上 |
Exception getException() |
返回當前頁的 Exception 對象 |
ServletRequest getRequest() |
返回當前頁的 request 對象 |
ServletResponse getResponse() |
返回當前頁的 response 對象 |
ServletConfig getServletConfig() |
返回當前頁的 ServletConfig 對象 |
HttpSession getSession() |
返回當前頁的 session 對象 |
Object getPage() |
返回當前頁的 page 對象 |
ServletContext getServletContext() |
返回當前頁的 application 對象 |
public Object getAttribute(String name) |
獲取屬性值 |
Object getAttribute(String name,int scope) |
在指定的范圍內獲取屬性值 |
void setAttribute(String name,Object attribute) |
設置屬性及屬性值 |
void setAttribute(String name,Object obj,int scope) |
在指定范圍內設置屬性及屬性值 |
void removeAttribute(String name) |
刪除某屬性 |
void removeAttribute(String name,int scope) |
在指定范圍內刪除某屬性 |
void invalidate() |
返回 servletContext 對象,全部銷毀 |
pageContext 對象的主要作用是提供一個單一界面,以管理各種公開對象(如 session、application、config、request、response 等),提供一個單一的 API 來管理對象和屬性。
例1:通過 pageContext 對象取得不同范圍的屬性值,代碼如下:
<%@ page contentType="text/html;charset=utf-8" %>
<html>
<head>
<title>
pageContext 對象獲取不同范圍屬性
</title>
</head>
<body>
<%
request.setAttribute("info","value of request scope");
session.setAttribute("info","value of request scope");
application.setAttribute("info","value of application scope");
%>
利用 pageContext 取出以下范圍內各值(方法一):<br>
request 設定的值:<%=pageContext.getRequest().getAttribute("info") %> <br>
session 設定的值:<%=pageContext.getSession().getAttribute("info") %> <br>
application 設的值:<%=pageContext.getServletContext().getAttribute("info") %> <hr>
利用pageContext取出以下范圍內各值(方法二):<br>
范圍1(page)內的值:<%=pageContext.getAttribute("info",1) %> <br>
范圍2(request)內的值:<%=pageContext.getAttribute("info",2) %> <br>
范圍3(session)內的值:<%=pageContext.getAttribute("info",3) %> <br>
范圍4(application)內的值:<%=pageContext.getAttribute("info",4) %> <hr>
利用 pageContext 修改或刪除某個范圍內的值:
<% pageContext.setAttribute("info","value of request scope is modified by pageContext",2); %> <br>
修改 request 設定的值:<br>
<%=pageContext.getRequest().getAttribute("info") %> <br>
<% pageContext.removeAttribute("info"); %>
刪除 session 設定的值:<%=session.getAttribute("info") %>
</body>
</html>
運行結果如圖 1 所示。
圖1 通過pageContext對象取得不同范圍的屬性值
提示:
pageContext 對象在實際 JSP 開發過程中很少使用,因為 request 和 response 等對象可以直接調用方法進行使用,而通過 pageContext 來調用其他對象,會覺得有些麻煩。