Java EE 6 supports a suite of five scopes, each with its own behavior for managing the user's interaction with a Java Web application. Find out how and when to use them.

WEBINAR:On-Demand

As you probably know, scopes are a very important aspect of a Web application. The scope notion represents the idea that an object belongs to a certain part of an application. So, you can use scopes for holding state over the duration of the user's interaction with the application. In Java Web applications, request and session scopes are the most commonly used but the Java EE 6 specification supports a suite of five scopes, any of which can accept an object.

In this article, I will present each of the Java EE 6 scopes in the context of a Java Bean and I will demonstrate its behavior through a simple JSF/XHTML page.

Java EE 6 Scopes Overview

The Java EE 6 scopes are summarized in the table below, which presents the scope annotation, scope class and a short description for each one. I will detail each of them in the sections to follow.

Scope

Scope Class

Scope Annotation

Short Description

Dependent

javax.enterprise.context.DependentScoped

@Dependent

Default scope

Request

javax.enterprise.context.RequestScoped

@Request

Single HTTP request/user

Session

javax.enterprise.context.SessionScoped

@Session

Multiple HTTP requests/user

Conversation

javax.enterprise.context.ConversationScoped

@Conversation

A short-lived/controlled session

Application

javax.enterprise.context.ApplicationScoped

@Application

All users share the same state

Java EE 6 Request Scope

The request scope is very useful in any Web application, and an object defined in the request scope usually has a short lifespan. When the container accepts an HTTP request from the client, the specified object is attached to the request scope and it is released when the container has finished transmitting the response to that request. A new HTTP request always comes in a new request scope object. In short, a request scope represents a user's interaction with a Web application in a single HTTP request.

In Java EE 6, you place a Java Bean under the request scope by annotating the Bean with @RequestScoped and importing the javax.enterprise.context.RequestScoped class. For example, this Bean generates random numbers and stores them in an ArrayList:

Most importantly, you can't keep a list of generated numbers because for every request a new Bean instance is created and a new empty list is created and filled with only the last random number generated. This makes the list useless.