Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of @ViewScoped in JSF 2.0?

Tags:

java

jsf

How to use / advantages of using @ViewScoped below the @ManagedBean in JSF 2.0

like image 921
Anand Devaraj Avatar asked Dec 03 '11 10:12

Anand Devaraj


1 Answers

@ManagedBean just declares that a certain bean is managed by JSF (makes it available to expression language among others).

@ViewScoped lets you declare a specific scope the bean will live in. The default (when you don't specify any scope) is @RequestScoped, which means your bean will live through a single request and will then be destroyed. Other scopes are @SessionScoped and @ApplicationScoped. Third party extensions have introduced other scopes.

@ViewScoped will keep living as long as you post back a page to itself. A 'view' is another word for 'page' in Java EE, but page scope already meant something else in Java EE. The view scope is very convenient, since it allows the pattern of initializing data when you first access a page (via a non-faces request, which is typically a GET request) and then keep that data when you work on the page, doing postbacks, AJAX requests, etc.

The scope is a lifesaver when working with tables in JSF where you interact with components in the table. Namely, in JSF there is a rule that the data that was used to render the table must be the EXACT SAME data that is used after the postback when processing the components you interacted with. With the view scope this is trivial, but without it it's rather tricky.

like image 181
Arjan Tijms Avatar answered Sep 27 '22 19:09

Arjan Tijms