If you have been using JSF for a while, you know that in some instances, request scope is too short and session scope is too long to store objects. This of course applies to a situation where you need to keep some data for longer than a request but less than session. If you use Seam or Spring, then you get conversation and view scopes which solve this problem. JSF 2.0 also comes with view scope. If you are using JSF 1.2 with just managed beans, and at this point I’m guessing that’s basically everyone (meaning you are not using JSF 2 yet), then you are kind of stuck.
Luckily RichFaces comes with a view scope. View scope means you can keep the object alive as long as you are staying on the view (page). The bean is saved as an attribute of the JSF view. When the JSF view (its state) is saved, the bean is saved as well. When the view is restored, the bean is restored and placed back in request scope.
There are two ways place a bean in view scope. One is using a4j:keepAlive tag, second is to use @KeepAlive annotation. Let’s see how both are used. Our one page application is a list of any random words. Words can added and deleted (more screen shots at the end).
Bean:
package example; import java.util.ArrayList; import javax.annotation.PostConstruct; public class Bean { private ArrayList words; private String selectedWord; private String newWord; public void delete (){ words.remove(selectedWord); } public void add (){ words.add(newWord); } @PostConstruct public void create () { words = new ArrayList (); words.add("Hello"); words.add("World"); words.add("Peace"); words.add("Soccer"); words.add("JSF"); } public String getNewWord() { return newWord; } public void setNewWord(String newWord) { this.newWord = newWord; } public ArrayList getWords() { return words; } public void setSelectedWord(String selectedWord) { this.selectedWord = selectedWord; } }
Registering the bean, placing it in request scope:
bean example.Bean request
JSF page:
On line 2, a4j:keepAlive tag points to managed bean name that will be saved with the view thus giving us view scope. When this page is restored (as a result of add or delete action), bean managed bean will be re-created and placed in request scope. Without the view scope, after any action add or delete we would always see the original list of values as the bean would be re-created on each request.
Instead of using a4j:keepAlive tag, we can also use @org.ajax4jsf.model.KeepAlive annotation:
package example; import java.util.ArrayList; import javax.annotation.PostConstruct; @org.ajax4jsf.model.KeepAlive public class Bean { private ArrayList words; private String selectedWord; private String newWord; // rest of code... }
Lastly, a4j:keepAlive tag comes with just one attribute:
When set to true, bean value is restored for AJAX requests only.
Screen shots
Running for the first time:
After entering ‘Flowers’ and clicking Add:
After deleting ‘JSF’:
Leave a comment