數據在不同生命週期需要不同可見範圍。搞清四大域的「多大、幹什麼、怎麼用、為什麼」,是 Web 開發基本功。
| 作用域 | 對應對象 | 生命週期/範圍 | 典型用途 |
|---|---|---|---|
| application | ServletContext | 整個 Web 應用 (容器啟動~關閉) | 全局配置、緩存、共享資源 |
| session | HttpSession | 一次會話 (默認 30 分鐘無操作失效) | 用戶登錄狀態、購物車、多步驟表單 |
| request | ServletRequest | 一次請求鏈 (含 forward) | Controller → View 傳遞數據 |
| page | PageContext | 單個 JSP 頁面渲染期間 | 頁面級臨時變量、標籤協作 |
application.setAttribute("key", val) / getAttribute("key")web.xml <context-param>getResourceAsStream("/path")setAttribute/getAttribute、setMaxInactiveInterval(秒)、invalidate() 銷毀。web.xml <session-config><session-timeout>30</session-timeout></session-config> (分鐘)。setAttribute 傳遞數據到 JSP。pageContext.getRequest()、getSession()、getServletContext() 可拿到其它八大隱式對象。pageContext.getAttribute("key", scope),scope: 1=page, 2=request, 3=session, 4=application。findAttribute("key") 從 page→request→session→application 返回首個找到值。pageContext.forward() / sendRedirect()。<%@ page contentType="text/html;charset=UTF-8" %>
<%
pageContext.setAttribute("name","地球"); // page
request.setAttribute("name","太陽系"); // request
session.setAttribute("name","銀河系"); // session
application.setAttribute("name","宇宙"); // application
%>
page: <%=pageContext.getAttribute("name")%><br>
request: <%=pageContext.getRequest().getAttribute("name")%><br>
session: <%=pageContext.getSession().getAttribute("name")%><br>
application: <%=pageContext.getServletContext().getAttribute("name")%><br>
scope=1: <%=pageContext.getAttribute("name",1)%><br>
scope=2: <%=pageContext.getAttribute("name",2)%><br>
scope=3: <%=pageContext.getAttribute("name",3)%><br>
scope=4: <%=pageContext.getAttribute("name",4)%><br>
<% pageContext.removeAttribute("name",3); %>
session after remove: <%=session.getAttribute("name")%><br>
<% pageContext.setAttribute("name","多元宇宙",4); %>
application after set: <%=application.getAttribute("name")%><br>
findAttribute: <%=pageContext.findAttribute("name")%><br>
getAttributesScope: <%=pageContext.getAttributesScope("name")%><br>
page: 地球 request: 太陽系 session: 銀河系 application: 宇宙 scope=1: 地球 scope=2: 太陽系 scope=3: 銀河系 scope=4: 宇宙 session after remove: null application after set: 多元宇宙 findAttribute: 地球 getAttributesScope: 1
最小作用域原則:能用 request 別用 session,能用 session 別用 application,減少併發風險與記憶體佔用。