Insights into Java Server Faces

2013/01/15

Howto use PreRenderViewEvent on a component or any managed bean

Filed under: JSF — Hanspeter @ 23:15

JSF 2.0 introduced many events, one of it is javax.faces.event.PreRenderViewEvent. But there is a pitfall – listeners for this event are registered in application scope. Therfore one must be very carefull to not subscribe any UIComponent or managed bean as listener for PreRenderViewEvent. However, sometimes it’s required to do something during PreRenderViewEvent processing on a UIComponent – for example modify the completely built component tree e.g. using some rules.

We need something to decouple the application scoped PreRenderViewEvent listener from the UIComponent’s or scoped managed beans. For this I created a PreRenderViewEventMediator – an application scoped listener to PreRenderViewEvent to mediate the event to request scoped subscribed PreRenderViewEventListener – an additional interface that must be implemented by subscribers for the mediated PreRenderViewEvent. To get this working PreRenderViewEventMediator must be configured to subscribe to PreRenderViewEvent – using faces-config.xml (iin current JSF 2.1.x @ListenerFor did not work) – e.g.:

  <application>
    <system-event-listener>
      <system-event-class>javax.faces.event.PreRenderViewEvent</system-event-class>
      <system-event-listener-class>ch.dueni.faces.event.PreRenderViewEventMediator</system-event-listener-class>
    </system-event-listener>
  </application>

Now any class that wants to subsribe to PreRenderViewEvent may simply use PreRenderViewEventMediator.subscribe(this); – as shown in the SimpleListener below. Unsubscribe is not necessary since PreRenderViewEventMediator manages the subscribed listeners on request scope –

@ManagedBean
@RequestScoped
public class SimpleListener implements PreRenderViewEventListener {

  @PostConstruct
  public void subsribe() {
    PreRenderViewEventMediator.subscribe(this);
  }

  @Override
  public void processPreRenderViewEvent(FacesContext jsf) {
    // do what need to be done during PreRenderViewEvent processing
  }
}

Imagination is more important than knowledge. For knowledge is limited. [Albert Einstein]

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: