In JSP, variable scopes define where and how long a variable (object) is available during the lifecycle of a web application.
There are four variable scopes in JSP:
| Scope | Object Availability | Lifetime |
|---|---|---|
| page | Available only in the current page | Until the page finishes processing |
| request | Available for the current HTTP request | Until the request is completed (forwarded or responded) |
| session | Available for the current user session | Until the session times out or is invalidated |
| application | Available for all users, all sessions | Until the server shuts down or app is undeployed |
🔵 1. page Scope
- Visible only in the current JSP page.
- Not shared across requests or other pages.
Example:
<jsp:useBean id="user" class="com.example.User" scope="page" />
user exists only while this JSP page is executing.
After the response is sent, it disappears.
🔵 2. request Scope
- Shared across the entire request, including forwards and includes.
- Used to pass data between servlets, filters, and JSPs.
Example:
<jsp:useBean id="user" class="com.example.User" scope="request" />
If you forward the request to another page, it can still access user.
🔵 3. session Scope
- Persists across multiple requests from the same user/browser session.
- Good for storing user login data, shopping carts, etc.
Example:
<jsp:useBean id="user" class="com.example.User" scope="session" />
user stays available until the session expires (usually after inactivity).
🔵 4. application Scope
- Global scope — available to all users and sessions within the web application.
- Useful for application-wide settings, counters, shared resources.
Example:
<jsp:useBean id="config" class="com.example.Config" scope="application" />
config is visible everywhere in the app until the server restarts or app is undeployed.
📚 Summary Table
| Scope | Object tied to | Accessed from | Lifetime |
|---|---|---|---|
page | Current JSP page | Only the current page | Until page response completes |
request | HTTP Request object | Forwarded/Included pages too | Until request completes |
session | User’s Session object | All pages in session | Until session timeout |
application | Application Context | All pages and all users | Until server shutdown |
📢 How They Relate to Java Objects
In Java code inside JSPs, you access them using:
pageContext→ forpagescoperequest→ forrequestscopesession→ forsessionscopeapplication→ forapplicationscope
Example in JSP:
<%= session.getAttribute("user") %>
<%= request.getAttribute("orderId") %>
<%= application.getAttribute("config") %>
🎯 Final Key Points:
- Use page for local temporary data.
- Use request for passing data between pages.
- Use session for user-specific long-term data.
- Use application for global shared data.