Skip to main content

JSF Tip #21 - The JSF StateHolder API

Posted by mriem on October 17, 2012 at 6:33 PM PDT

The definition of a StateHolder according to the StateHolder interface:

  boolean isTransient()
  void restoreState(FacesContext context, Object state)

  Object saveState(FacesContext context)
  void setTransient(boolean newTransient)

Each of the methods mentioned above have a particular role to fulfill during the JSF lifecycle.

Transient or not

The setTransient method can be used to state whether or not this StateHolder participates in state saving (true) or not (false). The isTransient method can be used to inspect that.

Save and restore

The saveState method is called by the runtime to save the StateHolder. Note the return value of this method should be Serializable. The restoreState method is called by the runtime to restore the StateHolder.

Example

  ...
 
  boolean isTransient() {
    return transientFlag;
  }

  void restoreState(FacesContext context, Object state) {
    getAttributes().put("test", (String) state);
  }

  Object saveState(FacesContext context) {
    Object state = (Object) getAttributes().get("test");
  }

  void setTransient(boolean newTransient) {
    transientFlag = newTransient;
  }

  ...

Caution

The restoreState and saveState methods are tightly coupled and as such should be called within the same call hierarchy.