A mistake is to not associate/interpret correctly the Jsf Lifecycle Phases with the Listen Events Types; you have to know which events takes place in which JSF phase. Per example, the below component registers itself as a listener for the PreValidateViewEventevent, and by default to the PostRestoreStateEventevent:
@FacesComponent(value = TomComponent.COMPONENT_TYPE, createTag = true)
public class TomComponent extends UIComponentBase
implements ComponentSystemEventListener {
public Static Final String COMPONENT_FAMILY =
"jsf.uicomponentwithsubscribetoevent";
public static final String COMPONENT_TYPE =
"uicomponentwithsubscribetoevent.TomComponent";
@PostConstruct
public void tomSubscribeToEvent() {
subscribeToEvent(PreValidateEvent.class, this);
}
@Override
public void processEvent(ComponentSystemEvent event)
throws AbortProcessingException {
System.out.println("EVENT EMITTED: " + event);
}
@Override
public void encodeEnd(FacesContext context) throws IOException {
ResponseWriter responseWriter = context.getResponseWriter();
responseWriter.write("I'm Tom the cat!");
}
@Override
public String getFamily() {
return COMPONENT_FAMILY;
}
}
Well, at initial request JSF executes only the Restore View (there is nothing to restore now) and RenderResponse phases, which means that the TomComponent doesn't emit any of PreValidateViewEventand PostRestoreStateEventevents. Actually, at initial request TomComponent subscribes to PostRestoreStateEvent and PreValidateViewEvent - component system event listeners are by default saved in JSF state and thus inherently view scoped. If you didn't know that, then you may think that the application is not working correctly. At postbacks instead, the Restore View (which restore the component tree now) and the Process Validations phase are executed, so both events are emitted and the output will be like this:
EVENT EMITTED: javax.faces.event.PostRestoreStateEvent
[source=uicomponentwithsubscribetoevent.TomComponent]
EVENT EMITTED: javax.faces.event.PreValidateEvent
source=uicomponentwithsubscribetoevent.TomComponent]
Obviously, the PostRestoreStateEventfirst!
If you need a request scoped listener you may want to check the OmniFaces, Events#subscribeToRequestComponentEvent(), which subscribes the given callback instance to the given component that get invoked only in the current request when the given component system event type is published on the given component.