Monday, April 2, 2012

New Scopes in JSF2.x


New Scopes in JSF2.x

In JSF2, beans can defined in two additional scopes apart from the existing scopes (request, session and application scope). Those are View Scope and Flash Scope

ViewScope:
  1. Defining a bean in view scope: Bean can be defined in view scope using the annotation @ViewScoped (javax.faces.bean.ViewScoped). Beans can be defined through annotations from JSF2 and is not required to define in the faces-config.xml file.

  2. Beans of viewscope shall be alive till the current view (page) is active. That is the bean shall be alive till the user interacts with the same page and doesn’t navigate to new view (page).

  3. The scope of viewscope is higher than the request and less to session scope.

  4. If the same page is returned in the action method, the bean shall be dead and shall not be retained in view scope, since the same view is recreated again.

FlashScope:
  1. The object placed in the flash scope shall be retained till the next request cycle. Thereafter it is destroyed. It is handy and most commonly used for post-redirect-get cycle where the messages need to be transferred to the request on a redirect

  2. Placing object in a FlashScope: (in the below example also note the redirection done using the the attribute “faces-redirect=true”
  3. public String save() {
    Flash flash=FacesContext.getCurrentInstance().getExternalContext().getFlash();
    flash.put("name",this.name);
    return "welcome?faces-redirect=true";
    }

  4. The flash scoped objects shall accessed using the EL object flash.
    <h:outputLabel value="Hi #{flash.name}"</h:outputLabel>


No comments:

Post a Comment