Sunday, July 08, 2012

JSF Tip of the Day: @ViewScoped and @ConversationScoped Usage

Abstract

A question that often comes up is when and where to use a particular scope in JSF. This has become even muddier with the addition of CDI support in JSF. In the upcoming release of Java EE 7, there will be even more scopes to consider. This example code demonstrates using @ViewScoped and @ConversationScoped.

Explanation

@ViewScoped

If you want to have the information on the page to update, and you are not navigating away from the page; a clear choice is the use of @ViewScoped. This is particularly true when the page is heavily dependent on AJAX. This allows partial-page submission for validation for example without losing the data contained on the page.

@ConversationScoped

@ConversationScoped scoped bean is for a long running process where there is a definite beginning and end. A perfect example is a wizard, or checking out of an online store.

The conversation begins when you click "Pay" and ends when you are given your receipt, or order information. Another example would be a complex series of wizards where there are multiple pages to complete the process. The point to keep in mind is that you have a clear bounds to start and end with.

Description

In this example code, I have a list of family members which are in different scopes depending on which example you pick. In the @ViewScoped bean you can delete people from the list and it maintains the list of changes unless you navigate away from the page. Then the list is reset back to the original values. In the @ConversationScoped bean, once you navigate to the page, a conversation begins. This will allow you to modify the list of names, and navigate to different pages and back without losing your data. Once you click on the End button, the conversation ends.

Code

The project was developed using NetBeans 7 IDE and Apache Maven. The project was tested on GlassFish 3.1.2.

The code for the project can be downloaded here: scope-examples.zip

viewscope.xhtml



conversation.xhtml



ViewScopeBean.java



ConversationBean.java


1 comments :

John Yeary said...

I was asked by a friend why I have @Named and @ManagedBean in the @ConversationScoped bean.

I replied that a @Named bean is a @ManagedBean, but that a @ManagedBean is not a @Named bean.

You can choose to expose the CDI bean out to the JSF layer with a @Named annotation, but at some point you could decide to turn it off.

This may change it JSF 2.2 when it is released.

Popular Posts