Nearby lessons
9 of 30JSP - Scopes (page, request, session, application)
📌 What You Will Learn
- Understand the 4 JSP scopes and their lifecycles
- Know which scope object manages each scope
- Use findAttribute() to search across all scopes
JSP Scopes determine how long an attribute lives and which components can access it. JSPs have 4 scopes — more than Servlets' 3 — and the pageContext object manages them all.
4 JSP Scopes
| Scope | Managed By | Available To | Lifecycle |
|---|---|---|---|
| Page | pageContext | Current JSP only | Single request |
| Request | request | Current request (all forwarded/included JSPs) | Single request |
| Session | session | All requests from the same client | Until session expires |
| Application | application | All components in the web app | Until server shutdown |
Scope Lifecycle
- Request scope: starts at request creation, ends when request processing completes. Attributes are destroyed after
service()finishes. - Session scope: starts when session is created, ends on logout (
invalidate()) or timeout. - Application scope: starts at deployment/server startup, ends at undeployment/shutdown.
- Page scope: starts and ends with the current JSP page (most restricted).
Attribute Management Methods
All scope objects support the same 4 methods:
Example03
PageContext Scope Constants
The PageContext class defines scope constants for use with its methods:
Example04
PageContext Attribute Methods
PageContext provides extra methods to manage attributes in any scope by specifying the scope constant:
Example05
findAttribute() — The All-Rounder
pageContext.findAttribute("name") searches all 4 scopes in order:
- Page scope
- Request scope
- Session scope
- Application scope
Returns the value of the first match found, or null if not found in any scope.
Demo Program
Setting attributes in all 4 scopes and reading them:
Example07
findAttribute() Demo
Setting the same attribute name in all scopes — findAttribute() returns the page scope value:
Example08
📝 Key Takeaways
- Page scope is most restricted; application scope is least restricted
- findAttribute() searches page → request → session → application in order
- PageContext is the single point of contact for attribute management
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3