以下代码显示如何处理应用程序级事件。
JSF在JSF应用程序生命周期中有处理应用程序特定任务的系统事件侦听器。
我们可以通过实现SystemEventListener接口来处理系统级事件,并在faces-config.xml中注册system-event-listener类。
我们还可以通过传递f:event的监听器属性中的托管bean方法的名称来使用方法绑定来处理系统级事件。
以下代码显示了如何实现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中注册系统事件的自定义系统事件侦听器
<system-event-listener>
<system-event-listener-class>
com.lmonkey.common.CustomSystemEventListener
</system-event-listener-class>
<system-event-class>
javax.faces.event.PostConstructApplicationEvent
</system-event-class>
</system-event-listener>
下面的代码显示了处理系统级事件的方法绑定方式。
public void handleEvent(ComponentSystemEvent event){
data="Hello World";
}
使用上面的方法
<f:event listener="#{user.handleEvent}" type="preRenderView" />
以下代码来自MyListener.java。
package com.lmonkey.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);
}
}
以下代码来自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>
将生成的WAR文件从目标文件夹复制到Tomcat部署文件夹,并运行Tomcat-Install-folder/bin/startup.bat。
Tomcat完成启动后,在浏览器地址栏中键入以下URL。
http://localhost:8080/simple-webapp/demo.xhtml
© 著作权归作者所有