When should one use the preRenderView event to initialize data for a page versus using the viewAction? Are they equal in use and do they have the same effect?
preRenderView Event
<f:metadata>
<f:event type="preRenderView" listener="#{myBean.initialize}"/>
</f:metadata>
or
viewAction
<f:metadata>
<f:viewAction action="#{myBean.initialize}"/>
</f:metadata>
In practice, they can be used to achieve the same effect, but viewAction
(new with JSF2.2) comes with the following enhancements:
onPostback
: viewAction
comes with this attribute that allows you to specify whether you want the action to be executed on postback to the same view (that is, on page refresh or button submit etc). It defaults to false
, so you don't even have to specify it if you don't need to. To achieve the same effect with preRenderView
, you'll need
<f:metadata>
<f:event type="preRenderView" rendered="#{facesContext.postBack}" listener="#{myBean.initialize}"/>
</f:metadata>
phase
: this attribute allows you to specify that the action be executed during a specific JSF phase. It defaults to INVOKE_APPLICATION
, but all the other JSF Phase Ids are valid here.
if
: This attribute allows you to supply a value expression that evaluates to a boolean result. The view action will only be executed on the outcome of this expression.
immediate
: This attribute now grants the ability for a viewAction
to be executed during the APPLY_REQUEST_VALUES
phase (as against the default INVOKE_APPLICATION
phase), allowing it to behave like a regular UIComponent
Overall, the viewAction
is a cleaner design approach to carrying out view commands.