Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

J2EE pathfinder: Create and manage stateful Web apps

Proper handling of the four session scopes

Kyle Gabhart (kyle@gabhart.com), Consultant, Gabhart Consulting
Photo of Kyle Gabhart
Kyle Gabhart is an independent consultant and subject matter expert with J2EE, XML, and Web services technologies. Kyle is a popular public speaker, recognized for his enthusiasm and dynamic analysis and presentation of emerging technologies. Kyle can be reached at kyle@gabhart.com.

Summary:  Data management is key when creating stateful applications. And to intelligently manage user data, you must contextualize it, which is done with scopes. In this installment of J2EE pathfinder, Java developer and consultant Kyle Gabhart sheds some light on the proper handling of the four J2EE session scopes for stateful Web application development.

View more content in this series

Date:  30 Jul 2003
Level:  Intermediate

Comments:  

In this article, we'll follow up on the second installment in this series, "J2EE technologies for the stateful network," in which you learned some of the basics of stateful application development in J2EE. This time, we'll focus less on the big picture and more on how we create and manage a stateful user experience.

One of the prime components of creating stateful applications is data management. By collecting data about a user throughout a session, we are able to create a profile of that user, and then use that profile to personalize his or her experience. In order to intelligently manage user data, we have to contextualize it; and for this we use scopes.

In J2EE there are four scopes, or contexts, for managing data: application, session, request, and page. This month, you'll learn what each of the scopes brings to stateful application development in J2EE, and where each one best fits in terms of the different session management scenarios.

We'll get started with a quick review of stateful Web application development in J2EE.

Building stateful Web applications

If users only needed the Web to view static content, then we wouldn't need any other technology but HTML. But most users want a lot more out of the Web than text-based information and nice background colors. In fact, the majority of users today come to the Web to perform sophisticated e-commerce transactions, engage in online communities, download (and upload) media, and more. Interactivity is the key to most popular Web sites, and the more personalized the features the better. For this type of development we use advanced Web technologies such as CGI, PHP, ASP, JSP, and Java Servlets.

An important component of interactivity is personalization. A personalized Web site has the ability to customize both content and delivery to suit a user's particular needs and interests. An important component of personalization is duration. The user experience should not only be cohesive, but it should extend beyond a single transaction. For example, when you log on to a personalized portal like Yahoo, you establish an identity, and no matter where you travel in the Yahoo domain, your identity remains intact. The same is true for many online banking, credit-card, and stock-trading systems. Increasingly, online stores are also picking up this model.

When we talk about a user experience that extends beyond a single transaction, we call it a session. When we create Web applications that support sessions, rather than single, isolated transactions, we are creating stateful applications.

In a stateful application, a user may travel to many different parts of a site and perform multiple transactions, but he will always maintain his unique identity. This is possible because the system is constantly tracking the state of his transactions. In J2EE this type of development is managed by storing each user's information on a back-end data server. When a user logs onto the site for the first time, he establishes a unique ID. From that point forward, data associated with the user's ID is stored and can be accessed by the system as needed.

When writing to the Java platform, we can use one of three techniques to associate a user ID with an individual user: URL rewriting, hidden form fields, and HTTP cookies. In J2EE, we use the HTTPSession API to store, retrieve, and associate session data with a given user ID.

In addition to storing data, we must also be able to contextualize it. The term scope refers to the context of stored data (the data's "scope"); and the proper handling of scope is at the heart of stateful Web application design.


Session scopes

The term scope refers to a context in which data can be associated, or stored. In traditional stand-alone applications, there are several contexts (or scopes) in which variables and object references can be associated. Typical scopes include:

  • Local/method
  • Class/object/component
  • Package/library
  • Protected
  • Global/public

The concept of scope within the context of a Web application is different from its use in more traditional, stand-alone applications. In a Web application, scope refers to the degree to which an object is made available to an application's components. In stand-alone applications, scope also refers to availability, but the scope is demarcated by code blocks.

In J2EE Web applications, there are four session scopes:

  • Page
  • Request
  • Session
  • Application

Each of the J2EE scopes has a context in which primitive data and object references can be associated (stored) for use by other components that share the same context. Table 1 lists the four scopes, along with their applicability to servlets and JSP pages, and a description of each scope:


Table 1. The four session scopes
Session scopeServletsJSP pagesDescription
PageNoYesRepresents the objects and attributes associated with a page. A page is represented by a single compiled Java servlet class (along with any include directives but not include actions). This includes both servlets and JSP pages compiled into servlets.
RequestYesYesRepresents the objects and attributes associated with a request initiated by the Web client. A request may span multiple pages involving several Web components (due to forward directives and include actions).
SessionYesYesRepresents the objects and attributes associated with a single user experience for a Web client. A Web session can and often will span multiple client requests.
ApplicationYesYesRepresents the objects and attributes associated with an entire Web application. This is essentially a global scope spanning an entire Web application across multiple pages, requests, and sessions.

Next, we'll look at the different mechanisms for storing data in the four scopes.


Storing data in a scope

Each of the four scopes has a different mechanism for storing and ultimately accessing contextual data. Each scope has a single class through which contextual data is stored and retrieved. Table 2 identifies the four class types that correspond to the four session scopes:


Table 2. Class types for storing scoped data
Class nameScopeNotes
javax.servlet.jsp.PageContextPage A JSP-specific type representing the current JSP page. PageContext is an abstract class, designed to be extended by JSP engine vendors to provide implementation-specific types. A PageContext instance provides access to all the namespaces associated with a JSP page.
javax.servlet.http.HttpServletRequestRequestThis type represents the current HTTP request. The HttpServletRequest type is an interface, designed to be implemented by servlet-engine vendors. Request-specific data (request method, URI, HTTP parameters, and so on) provided by the client, as well as data supplied by another servlet or JSP page, can be stored within a request scope.
javax.servlet.http.HttpSessionSession This type represents the current HTTP session. The HttpSession type is an interface, designed to be implemented by servlet-engine vendors.
javax.servlet.ServletContextApplication This type represents the entire run-time Web module. The ServletContext type is an interface, designed to be implemented by servlet engine vendors.

At first glance, it might seem that using these four data types to store scoped data would be pretty straightforward. The trouble is, it's not always so clear which scope is most appropriate for a given scenario. We'll conclude with a look at some of the common scenarios you may encounter, as well as a practical discussion of which scope best suits each circumstance.


Scope solutions

Each of the four scopes defined by the JSP and Java Servlet specifications serves it own distinct purpose in a Web application.

  • Page provides a context that represents a single JSP page, and often has a one-to-one mapping with an actual page that is viewed by the user. This scope only applies to JSP pages, and it is the default scope for all objects, including JavaBeans components. Objects with page scope will typically be bound to a local variable to be accessed within scriptlets, expressions, JavaBean tags, and custom tags. If a reference to a page-scoped object must be obtained, a getAttribute() call can be made on the page's javax.servlet.jsp.PageContext variable.

  • Request is most suited to circumstances where a single user request may involve more than one servlet or JSP page. Request is a context capable of spanning multiple pages within the same atomic request. Request-scoped data is stored in the javax.servlet.ServletRequest object (using the javax.servlet.http.HttpServletRequest object) and is accessed using getAttribute() and setAttribute() methods.

  • Session is the heart and soul of stateful J2EE Web application scopes. It is this scope that enables the creation of persistent user experiences that span multiple requests. The javax.servlet.http.HttpSession object is the home for session-scoped data, and is accessible using getAttribute() and setAttribute() method calls. In order to use session-scoped data within a JSP page, you must first declare that the page participates in sessions. This can be accomplished by placing the JSP session attribute <%@ page session="true" %> anywhere in the page (typically at the very top).

  • Application is the longest-running scope. This is the closest that J2EE offers to global data. Application data is shared among all the Web components within a single application module. Objects with application scope are bound to the javax.servlet.ServletContext and accessed using getAttribute() and setAttribute() method calls.

With those definitions in mind, we can "scope out" some rules of thumb for using the different scopes:

  • Stick with page scope for your JSP data. This is the simplest way to work with JSP pages. Page is the default scope given to all data within your JSP page, and it allows you to use this data within the boundaries specified for local variables (class/method/local variable scope).

  • Be aware of the impact JSP includes have upon scope. Page scope applies to a single, compiled Java servlet class. Because include directives are processed at compile time, any content included in directives will operate in the context of the page scope. include actions, on the other hand, are processed at run time. The request scope should be used to share data between the two components if an include action is being used.

  • Use request scope to share data between Web components at run time. If a forward action or include action is used to share a request between two or more components, data can be shared between these components by scoping the data within the request context.

  • Use session scope to provide stateful user experience. Whether you are building an online store, an e-mail manager, a personalized information portal, or a financial management application, the session scope is ideally positioned for tracking a user from request to request and providing the user with a seamless, persistent environment.

  • Reserve application scope for global data. Application objects are static objects that are shared by all Web components within the application. The application scope should be used sparingly and reserved for data that truly needs to be shared between components and across user sessions. Typical examples include a cached DAO, cache of JNDI references, or any sort of common factory or other component that needs to use the Singleton pattern.

Conclusion

Proper handling of session scope -- that is, the context of the data being stored and maintained in a session -- is key to stateful application development. In this installment of J2EE pathfinder, I've identified the four J2EE session scopes and the various data types that can be used to represent each context, as well as discussing some of the practical considerations that will aid you in working with scopes.

Next month, we will examine the related subject of JSP implicit objects. Implicit objects are predefined and made available for every JSP page. Several of them provide access to the four scopes that we examined in this article. Until next month, happy pathfinding!


Resources

  • We got started on the topic of stateful application development way back in the beginning of the J2EE pathfinder series. See "J2EE technologies for the stateful network" (developerWorks, March 2003) if you need a refresher.

  • In his series "JSTL primer" (developerWorks, February-May 2003), Mark Kolb shows you how to use the JSP Standard Tag Library (JSTL) to avoid scripting elements in your JSP pages. Among other things, JSTL extends our capacity for working with scoped variables and implicit objects.

  • In "Struts, an open-source MVC implementation" (developerWorks, February 2001), Malcolm Davis starts at the beginning -- "A JSP file is a Java servlet" -- and then shows you how to use the powerful struts (servlet and JSP) framework in your J2EE programming.

  • You'll find hundreds of articles about every aspect of Java programming in the developerWorks Java technology zone.

About the author

Photo of Kyle Gabhart

Kyle Gabhart is an independent consultant and subject matter expert with J2EE, XML, and Web services technologies. Kyle is a popular public speaker, recognized for his enthusiasm and dynamic analysis and presentation of emerging technologies. Kyle can be reached at kyle@gabhart.com.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in

If you don't have an IBM ID and password, register here.


Forgot your IBM ID?


Forgot your password?
Change your password


By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)


By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology, Web development
ArticleID=10845
ArticleTitle=J2EE pathfinder: Create and manage stateful Web apps
publish-date=07302003
author1-email=kyle@gabhart.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).