IBM Skip to main content
Search for:   within 
      Search help  
     IBM home  |  Products & services  |  Support & downloads   |  My account

developerWorks > Java technology | Web architecture
developerWorks
J2EE pathfinder: Create and manage stateful Web apps
Discuss71 KBe-mail it!
Contents:
Building stateful Web applications
Session scopes
Storing data in a scope
Scope solutions
Conclusion
Resources
About the author
Rate this article
Related content:
J2EE pathfinder series
J2EE technologies for the stateful network
A JSTL primer, Part 1: The expression language
Subscriptions:
dW newsletters
dW Subscription
(CDs and downloads)
Proper handling of the four session scopes

Level: Intermediate

Kyle Gabhart (mailto:kyle@gabhart.com?cc=&subject=Create and manage stateful Web apps)
Consultant, Gabhart Consulting
30 July 2003

Column iconData 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. Share your thoughts on this article or any article in the J2EE pathfinder series in the accompanying discussion forum.

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 scope Servlets JSP pages Description
Page No Yes Represents 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.
Request Yes Yes Represents 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).
Session Yes Yes Represents 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.
Application Yes Yes Represents 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 name Scope Notes
javax.servlet.jsp.PageContext Page 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.HttpServletRequest Request This 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.HttpSession Session This type represents the current HTTP session. The HttpSession type is an interface, designed to be implemented by servlet-engine vendors.
javax.servlet.ServletContext Application 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

  • Participate in the discussion forum on this article. (You can also click Discuss at the top or bottom of the article to access the forum.)

  • 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.

  • Don't miss a single installment of J2EE pathfinder. See the column series page for a complete listing of past articles.

  • 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 GabhartKyle 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. For information on his recent and upcoming presentations or industry publications, visit Gabhart.com. Kyle can be reached at kyle@gabhart.com.


Discuss71 KBe-mail it!

What do you think of this document?
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Send us your comments or click Discuss to share your comments with others.



developerWorks > Java technology | Web architecture
developerWorks
  About IBM  |  Privacy  |  Terms of use  |  Contact