Java.Servlet.What variable scopes exist in JSP?

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:

ScopeObject AvailabilityLifetime
pageAvailable only in the current pageUntil the page finishes processing
requestAvailable for the current HTTP requestUntil the request is completed (forwarded or responded)
sessionAvailable for the current user sessionUntil the session times out or is invalidated
applicationAvailable for all users, all sessionsUntil 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

ScopeObject tied toAccessed fromLifetime
pageCurrent JSP pageOnly the current pageUntil page response completes
requestHTTP Request objectForwarded/Included pages tooUntil request completes
sessionUser’s Session objectAll pages in sessionUntil session timeout
applicationApplication ContextAll pages and all usersUntil server shutdown

📢 How They Relate to Java Objects

In Java code inside JSPs, you access them using:

  • pageContext → for page scope
  • request → for request scope
  • session → for session scope
  • application → for application scope

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.
This entry was posted in Без рубрики. Bookmark the permalink.