The following code shows how to handle application level events.
JSF has system event listeners to handle application specific tasks during JSF application Life Cycle.
We can handle the system level events by implementing SystemEventListener interface and register the system-event-listener class in faces-config.xml.
We can also use method binding to handle system level events by passing the name of the managed bean method in listener attribute of f:event.
The following code shows how to implement SystemEventListener Interface.
public class CustomSystemEventListener implements SystemEventListener { @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if(event instanceof PostConstructApplicationEvent){ System.out.println("Application Started. PostConstructApplicationEvent occurred!"); } } }
Then we can register custom system event listener for system event in faces-config.xml
<system-event-listener> <system-event-listener-class> com.java2s.common.CustomSystemEventListener </system-event-listener-class> <system-event-class> javax.faces.event.PostConstructApplicationEvent </system-event-class> </system-event-listener>
The following code shows the method binding way to handle system level events.
public void handleEvent(ComponentSystemEvent event){ data="Hello World"; }
Use above method
<f:event listener="#{user.handleEvent}" type="preRenderView" />
The following code is from MyListener.java.
package com.java2s.common; import javax.faces.application.Application; import javax.faces.event.AbortProcessingException; import javax.faces.event.PostConstructApplicationEvent; import javax.faces.event.PreDestroyApplicationEvent; import javax.faces.event.SystemEvent; import javax.faces.event.SystemEventListener; public class MyListener implements SystemEventListener{ @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if(event instanceof PostConstructApplicationEvent){ System.out.println("PostConstructApplicationEvent is Called"); } if(event instanceof PreDestroyApplicationEvent){ System.out.println("PreDestroyApplicationEvent is Called"); } } @Override public boolean isListenerForSource(Object source) { //only for Application return (source instanceof Application); } }
The following code is from demo.xhtml.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:body> <h2>This is start.xhtml</h2> </h:body> </html>
Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.
After Tomcat finish starting, type the following URL in the browser address bar.
http://localhost:8080/simple-webapp/demo.xhtml