Wednesday, August 6, 2014

How to call a method during various JSF lifecycle phases

In order to invoke a method during various lifecycle phases on JSF, you can either use JSF 2.0 <f:viewAction>tag. or <f:event> tag.
The functioning of both tags is very similar, both need a definition for trigger mechanism(when to invoke method) and action mechanism(which method to invoke). These tags are defined in in the meta definition section of the page as follows

<f:viewAction>

This action component specifies an application-specific command (or action), using an EL method expression, to be invoked during one of the JSF lifecycle phases,

<f:metadata>
  <f:viewAction phase="PROCESS_VALIDATIONS" action="#{person.init()}"/>
</f:metadata>

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


The above tag will result in person.init() method invoked before the "Process Validation" JSF lifecycle phase.

The init method (in the "Person" BackingBean) can be as follows:

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

The "phase" attribute can have one of the possible values.

  1. APPLY_REQUEST_VALUES
  2. PROCESS_VALIDATIONS 
  3. UPDATE_MODEL_VALUES 
  4. INVOKE_APPLICATION 

The default is INVOKE_APPLICATION.


<f:event> 

This specifies an application-specific action, using an EL method expression, to be invoked during one of the JSF lifecycle phases.

<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 "type" attribute can have one of the possible values.
  1. preRenderComponent
  2. preRenderView
  3. postAddToView
  4. preValidate  
  5. postValidate


<f:viewAction> differs from <f:event> in the following manner


  • View actions, by default is not invoked in post-backs; where as in f: event, post-backs needs to be programmatically checked.
  • View actions have navigation capabilities, View actions support both implicit and explicit navigation.  (action method returns backs a view or in xml), where as in f:event one needs to manage navigation programmatically using response.sendRedirect or using NavigationHandler
  • View actions can be triggered early on, before a full component tree is built, resulting in a lighter weight call.




2 comments: