JSF SystemEventListener Example

This tutorial shows you how to use the JSF SystemEventListener. A SystemEventListener can listen to many registered system events. Those system events can be fired by many kinds of sources (components). We can specify which SystemEventListener is used for which system event by doing a simple instanceof operator in the isListenerForSource method. This example shows how to ad a listener for application startup/shutdown.

JSF SystemEventListener for application startup/shutdown

The ApplicationListener implements the SystemEventListener which gives us two methods to override. The isListenerForSource is used to specify for which system events the class will handle. If returned true the processEvent method is invoked. With the instanceof operator we can check which event has been fired. In this example we want to listen for application startup and shutdown, so we check the SystemEvent with the PostConstructApplicationEvent and PreDestroyApplicationEvent respectively.

package com.memorynotfound.jsf;

import javax.faces.application.Application;
import javax.faces.event.*;

public class ApplicationListener implements SystemEventListener {

    @Override
    public void processEvent(SystemEvent event) throws AbortProcessingException {
        if (event instanceof PostConstructApplicationEvent){
            System.out.println("post initialize application");
        } else if (event instanceof PreDestroyApplicationEvent){
            System.out.println("pre destroy application");
        }
    }

    @Override
    public boolean isListenerForSource(Object source) {
        return source instanceof Application;
    }
}

Registering the JSF SystemEventListener

The listener should be configured in the faces-config.xml, as follows.

<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                                  http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2">

    <application>
        <system-event-listener>
            <system-event-class>javax.faces.event.PostConstructApplicationEvent</system-event-class>
            <system-event-listener-class>com.memorynotfound.jsf.ApplicationListener</system-event-listener-class>
        </system-event-listener>
        <system-event-listener>
            <system-event-listener-class>com.memorynotfound.jsf.ApplicationListener</system-event-listener-class>
            <system-event-class>javax.faces.event.PreDestroyApplicationEvent</system-event-class>
        </system-event-listener>
    </application>

</faces-config>

Demo

This is an example output of the application.

// when the application is initialized
post initialize application

// when the application is destroyed
pre destroy application

References

Download

You may also like...