JSF - Événements d'application

JSF fournit des écouteurs d'événements système pour effectuer des tâches spécifiques à l'application pendant le cycle de vie de l'application JSF.

S. Non Événement et description du système
1

PostConstructApplicationEvent

Se déclenche au démarrage de l'application. Peut être utilisé pour effectuer des tâches d'initialisation après le démarrage de l'application.

2

PreDestroyApplicationEvent

Se déclenche lorsque l'application est sur le point de s'arrêter. Peut être utilisé pour effectuer des tâches de nettoyage avant que l'application ne soit sur le point de s'arrêter.

3

PreRenderViewEvent

Se déclenche avant qu'une page JSF ne soit affichée. Peut être utilisé pour authentifier l'utilisateur et fournir un accès restreint à JSF View.

Les événements système peuvent être traités de la manière suivante.

S. Non Technique et description
1

SystemEventListener

Implémentez l'interface SystemEventListener et enregistrez la classe system-event-listener dans faces-config.xml

2

Method Binding

Passez le nom de la méthode du bean géré dans l' attribut écouteur de f: event.

SystemEventListener

Implémentez l'interface 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!");
      }      
   }
}

Enregistrez un écouteur d'événement système personnalisé pour l'événement système dans faces-config.xml.

<system-event-listener>
   <system-event-listener-class>
      com.tutorialspoint.test.CustomSystemEventListener
   </system-event-listener-class>
   
   <system-event-class>
      javax.faces.event.PostConstructApplicationEvent
   </system-event-class>    					
</system-event-listener>

Liaison de méthode

Définir une méthode

public void handleEvent(ComponentSystemEvent event) {
   data = "Hello World";
}

Utilisez la méthode ci-dessus.

<f:event listener = "#{user.handleEvent}" type = "preRenderView" />

Exemple d'application

Créons une application de test JSF pour tester les événements système dans JSF.

Étape La description
1 Créez un projet avec un nom helloworld sous un package com.tutorialspoint.test comme expliqué dans le chapitre JSF - Première application .
2 Modifiez le fichier UserData.java comme expliqué ci-dessous.
3 Créez le fichier CustomSystemEventListener.java sous un package com.tutorialspoint.test . Modifiez-le comme expliqué ci-dessous
4 Modifiez home.xhtml comme expliqué ci-dessous.
5 Créez faces-config.xml dans le dossier WEB-INF et modifiez-le comme expliqué ci-dessous. Gardez le reste des fichiers inchangés.
6 Compilez et exécutez l'application pour vous assurer que la logique métier fonctionne conformément aux exigences.
sept Enfin, créez l'application sous la forme d'un fichier war et déployez-la dans Apache Tomcat Webserver.
8 Lancez votre application Web en utilisant l'URL appropriée, comme expliqué ci-dessous à la dernière étape.

UserData.java

package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   private String data = "sample data";
	
   public void handleEvent(ComponentSystemEvent event) {
      data = "Hello World";
   }

   public String getData() {
      return data;
   }

   public void setData(String data) {
      this.data = data;
   }
}

CustomSystemEventListener.java

package com.tutorialspoint.test;

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 CustomSystemEventListener implements SystemEventListener {

   @Override
   public boolean isListenerForSource(Object value) {
      
      //only for Application
      return (value instanceof Application);
   }

   @Override
   public void processEvent(SystemEvent event) 
      throws AbortProcessingException {
      
      if(event instanceof PostConstructApplicationEvent) {
         System.out.println("Application Started. 
            PostConstructApplicationEvent occurred!");
      }
      
      if(event instanceof PreDestroyApplicationEvent) {
         System.out.println("PreDestroyApplicationEvent occurred.
            Application is stopping.");
      }
   }
}

home.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"
   xmlns:f = "http://java.sun.com/jsf/core">
   
   <h:head>
      <title>JSF tutorial</title>		   
   </h:head>
   
   <h:body> 
      <h2>Application Events Examples</h2>
      <f:event listener = "#{userData.handleEvent}" type = "preRenderView" />
      #{userData.data}
   </h:body>
</html>

faces-config.xhtml

<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
   xmlns = "http://java.sun.com/xml/ns/javaee"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
   version = "2.0">
   
   <application>
      <!-- Application Startup -->
      <system-event-listener>
         <system-event-listener-class>
            com.tutorialspoint.test.CustomSystemEventListener
         </system-event-listener-class>
         <system-event-class>
            javax.faces.event.PostConstructApplicationEvent
         </system-event-class>    					
      </system-event-listener> 
      
      <!-- Before Application is to shut down -->
      <system-event-listener>
         <system-event-listener-class>
            com.tutorialspoint.test.CustomSystemEventListener
         </system-event-listener-class>
         <system-event-class>
            javax.faces.event.PreDestroyApplicationEvent
         </system-event-class>    					
      </system-event-listener>
   </application>
</faces-config>

Une fois que vous êtes prêt avec tous les changements effectués, laissez-nous compiler et exécuter l'application comme nous l'avons fait dans le chapitre JSF - Première application. Si tout va bien avec votre application, cela produira le résultat suivant.

Regardez dans la sortie de votre console de serveur Web. Vous verrez le résultat suivant.

INFO: Deploying web application archive helloworld.war 
Dec 6, 2012 8:21:44 AM com.sun.faces.config.ConfigureListener contextInitialized 

INFO: Initializing Mojarra 2.1.7 (SNAPSHOT 20120206) for context '/helloworld' 
Application Started. PostConstructApplicationEvent occurred! 
Dec 6, 2012 8:21:46 AM com.sun.faces.config.ConfigureListener 
$WebConfigResourceMonitor$Monitor <init> 

INFO: Monitoring jndi:/localhost/helloworld/WEB-INF/faces-config.xml 
for modifications 
Dec 6, 2012 8:21:46 AM org.apache.coyote.http11.Http11Protocol start 

INFO: Starting Coyote HTTP/1.1 on http-8080 
Dec 6, 2012 8:21:46 AM org.apache.jk.common.ChannelSocket init 
INFO: JK: ajp13 listening on /0.0.0.0:8009  

Dec 6, 2012 8:21:46 AM org.apache.jk.server.JkMain start 
INFO: Jk running ID = 0 time = 0/24  config = null 
Dec 6, 2012 8:21:46 AM org.apache.catalina.startup.Catalina start 
INFO: Server startup in 44272 ms