以下代碼顯示如何處理應(yīng)用程序級(jí)事件。
JSF在JSF應(yīng)用程序生命周期中有處理應(yīng)用程序特定任務(wù)的系統(tǒng)事件偵聽(tīng)器。
我們可以通過(guò)實(shí)現(xiàn)SystemEventListener接口來(lái)處理系統(tǒng)級(jí)事件,并在faces-config.xml中注冊(cè)system-event-listener類(lèi)。
我們還可以通過(guò)傳遞f:event的監(jiān)聽(tīng)器屬性中的托管bean方法的名稱(chēng)來(lái)使用方法綁定來(lái)處理系統(tǒng)級(jí)事件。
以下代碼顯示了如何實(shí)現(xiàn)SystemEventListener接口。
public class CustomSystemEventListener implements SystemEventListener { @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if(event instanceof PostConstructApplicationEvent){ System.out.println("Application Started. PostConstructApplicationEvent occurred!"); } } }
然后我們可以在faces-config.xml中注冊(cè)系統(tǒng)事件的自定義系統(tǒng)事件偵聽(tīng)器
<system-event-listener> <system-event-listener-class> cn.w3cschool.common.CustomSystemEventListener </system-event-listener-class> <system-event-class> javax.faces.event.PostConstructApplicationEvent </system-event-class> </system-event-listener>
下面的代碼顯示了處理系統(tǒng)級(jí)事件的方法綁定方式。
public void handleEvent(ComponentSystemEvent event){ data="Hello World"; }
使用上面的方法
<f:event listener="#{user.handleEvent}" type="preRenderView" />
以下代碼來(lái)自MyListener.java。
package cn.w3cschool.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); } }
以下代碼來(lái)自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>下載 Pre_PostConstructApplicationEvent.zip
將生成的WAR文件從目標(biāo)文件夾復(fù)制到Tomcat部署文件夾,并運(yùn)行Tomcat-Install-folder/bin/startup.bat。
Tomcat完成啟動(dòng)后,在瀏覽器地址欄中鍵入以下URL。
http://localhost:8080/simple-webapp/demo.xhtml
更多建議: