Wednesday, August 6, 2014

Call a method in Backing Bean prior to page rendering


A view is rendered by JSF engine in "Render Response Phase". In order to invoke a method right before a View is rendered in the "Render Response Phase", you can use jsf 2.0 <f:event>. This tag is defined in in the meta definition section of a page as follows

<f:metadata>
  <f:event type="preRenderView" listener="#{person.init()}"/>
</f:metadata>

The attributes "listener" and "type" of <f:event> define which method to invoke for an event.
 listener: EL method expression i.e. method to invoke. e.g.#{person.init()}
 type: Name of the event for which to install a listener.

As a result of the above <f:event> declaration, JSF run-time invokes person.init() prior to rendering the components.

The init method (in the "Person" BackingBean) is shown as follows:

public void init() {        
  // do something like get List of persons from database
}

The JSF run-time invokes the method defined by listener, as per the event "type". "type" attribute can take one of the following values

  1. postAddToView:  runs right after the component is added to view during view build time (which is usually during restore view phase, but can also be during render response phase, e.g. navigation).
  2. preValidate:  runs right before the component is to be validated (which is usually during validations phase, but can also be apply request values phase if immediate="true").
  3. postValidate: runs right after the component is been validated (which is usually during validations phase, but can also be apply request values phase if immediate="true").
  4. preRenderView: runs right before the view is rendered during render response phase.
  5. preRenderComponent: runs right before the component is rendered during render response phase.
Note: Above list is from Balusc response on StackOverFlow(http://stackoverflow.com/questions/13999099/jsf-execution-order-of-fevents)


1 comment: