Extreme Java When vanilla Java is not enough

29Dec/090

Conversational Scope on JSF 2.0 (without Custom Scope)

JSF 2.0 is finally out. One thing that you will notice is the absence of a "conversational" scope. That would solve a lot of problems I have, but, unfortunately, I must wait for the next release. Or not?

There's no silver bullet to solve it, but I found a simple workaround using "view" scoped beans. Works for most cases - unless you need redirection or other advanced requirements.

First, your "conversational" managed bean must be have a "view" scope:

@ManagedBean(name="tbean")
@ViewScoped
public class TBean {
  private String name;
  private String result;
 
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getResult() {
    return result;
  }
  public String sayHi() {
    result = "Hi, " + name;
    return "";
  }
}

No big deal: just a POJO with @ViewScoped. The catch is you must return empty on your action. The view is simple, too:

<h:body>
  <h:form rendered="#{empty tbean.result}">
    Name: <h:inputText value="#{tbean.name}"/>
    <h:commandButton value="hi!"
        action="#{tbean.sayHi}"/>
  </h:form>
  <h:panelGroup rendered="#{not empty tbean.result}">
    <h1><h:outputText value="#{tbean.result}"/></h1>
    <h:button value="back" outcome="index"/>
  </h:panelGroup>
</h:body>

Nothing really new: classic JSF 1.0 magic tricks with the rendered attribute. The real catch, although, is the view scope. The bean will remain as long as you keep the current view (by returning empty on your actions). The "back" button clears the form and conditionally rendered components will give the feel of different pages.

This means you can easily have an three-page CRUD (list, view, edit), or an wizard-style page, that will reset when you enter it and keep state as long as you stay on "subpages".

Your page will grow fast using this method, but, since Facelets support is now native, you can use to keep this solution modular.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)


*

No trackbacks yet.