Storing data in your JSF 2.0 application

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

In this tutorial we will compare the available options for storing Object data into a Web application, showing at first the core JSF 2 scopes and the extension provided by CDI.

Core JSF scopes

JSF 2.0 specification defines the following scope scopes for storing data:

@RequestScoped
@ViewScoped
@SessionScoped
@ApplicationScoped
@CustomScope

Using the Request scope is quite straightforward: all you need in including the @RequestScoped annotation into your Bean. The most typical use of a @RequestScoped bean is as a JSF backing bean for a single page handling one HTTP request/response cycle. The vast majority of CDI beans you will use with JSF will likely belong to the request scope.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped

public class RequestManager {

}

jsf 2 cdi requestscope conversationscope sessionscope
On the other hand, @SessionScoped beans are used for objects that are used throughout the HTTP session. For example user details are typical information which are used all across the session so they are a typical canidate to be @SessionScoped:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class SessionManager {

}

jsf 2 cdi requestscope conversationscope sessionscope
One important addition introduced in JSF 2.0 API is the ViewScoped which is particularly useful when you are editing some objects while staying in the same page. In other words it's something broader then request but smaller then session, since this scope terminates if you navigate to other pages.

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class SessionManager {


}

As you can see, from the following picture, as long as we stay in the same JSF page, the data is preserved between requests. If we navigate to another page, the data is evicted from memory:

jsf 2 cdi requestscope conversationscope sessionscope

  A detailed example of a JSF 2.0 CRUD application which uses @ViewScoped can be found here.