JSF - valueChangeListener

Quando o usuário interage com componentes de entrada, como h: inputText ou h: selectOneMenu, o JSF dispara um valueChangeEvent, que pode ser tratado de duas maneiras.

S.Não Técnica e Descrição
1

Method Binding

Passe o nome do método de bean gerenciado no atributo valueChangeListener do componente UI.

2

ValueChangeListener

Implemente a interface ValueChangeListener e passe o nome da classe de implementação para o atributo valueChangeListener do componente UI.

Método de ligação

Defina um método

public void localeChanged(ValueChangeEvent e) { 
  
   //assign new value to country 
   selectedCountry = e.getNewValue().toString();  
}

Use o método acima

<h:selectOneMenu value = "#{userData.selectedCountry}"  onchange = "submit()" 
   valueChangeListener = "#{userData.localeChanged}" >
   <f:selectItems value = "#{userData.countries}" />
</h:selectOneMenu>

ValueChangeListener

Implementar ValueChangeListener

public class LocaleChangeListener implements ValueChangeListener {
   
   @Override
   public void processValueChange(ValueChangeEvent event)
      throws AbortProcessingException {
     
      //access country bean directly
      UserData userData = (UserData) FacesContext.getCurrentInstance().
      getExternalContext().getSessionMap().get("userData"); 
      userData.setSelectedCountry(event.getNewValue().toString());
   }
}

Use o método de ouvinte

<h:selectOneMenu value = "#{userData.selectedCountry}" onchange = "submit()">
   <f:valueChangeListener type = "com.tutorialspoint.test.LocaleChangeListener"
      />
   <f:selectItems value = "#{userData.countries}" />
</h:selectOneMenu>

Aplicação de exemplo

Vamos criar um aplicativo JSF de teste para testar o valueChangeListener no JSF.

Degrau Descrição
1 Crie um projeto com o nome helloworld sob um pacote com.tutorialspoint.test conforme explicado no capítulo JSF - Primeira Aplicação .
2 Modifique o arquivo UserData.java conforme explicado abaixo.
3 Crie o arquivo LocaleChangeListener.java em um pacote com.tutorialspoint.test . Modifique-o conforme explicado abaixo.
4 Modifique home.xhtml conforme explicado abaixo. Mantenha o resto dos arquivos inalterados.
5 Compile e execute o aplicativo para garantir que a lógica de negócios esteja funcionando de acordo com os requisitos.
6 Por fim, construa o aplicativo na forma de um arquivo war e implante-o no Apache Tomcat Webserver.
7 Inicie seu aplicativo da web usando o URL apropriado, conforme explicado a seguir na última etapa.

UserData.java

package com.tutorialspoint.test;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

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

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;
   private static Map<String,String> countryMap;
   private String selectedCountry = "United Kingdom"; //default value 

   static {
      countryMap = new LinkedHashMap<String,String>();
      countryMap.put("en", "United Kingdom"); //locale, country name
      countryMap.put("fr", "French");
      countryMap.put("de", "German");	
   }

   public void localeChanged(ValueChangeEvent e) {
      //assign new value to country
      selectedCountry = e.getNewValue().toString(); 
   }

   public Map<String, String> getCountries() {
      return countryMap;
   }

   public String getSelectedCountry() {
      return selectedCountry;
   }

   public void setSelectedCountry(String selectedCountry) {
      this.selectedCountry = selectedCountry;
   }
}

LocaleChangeListener.java

package com.tutorialspoint.test;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

public class LocaleChangeListener implements ValueChangeListener {
   
   @Override
   public void processValueChange(ValueChangeEvent event)
      throws AbortProcessingException {
      
      //access country bean directly
      UserData userData = (UserData) FacesContext.getCurrentInstance().
      getExternalContext().getSessionMap().get("userData");
      userData.setSelectedCountry(event.getNewValue().toString());
   }
}

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>valueChangeListener Examples</h2>
      
      <h:form>
         <h2>Method Binding</h2>
         <hr/>
         <h:panelGrid columns = "2">
            Selected locale :
            <h:selectOneMenu value = "#{userData.selectedCountry}"
               onchange = "submit()"
               valueChangeListener = "#{userData.localeChanged}" >
               <f:selectItems value = "#{userData.countries}" />
            </h:selectOneMenu>
            Country Name: 		 
            <h:outputText id = "country" value = "#{userData.selectedCountry}"
            size = "20" />		
         </h:panelGrid>
      </h:form>
   
   </h:body>
</html>

Assim que você estiver pronto com todas as mudanças feitas, vamos compilar e rodar a aplicação como fizemos no capítulo JSF - Primeira Aplicação. Se tudo estiver bem com sua aplicação, isso produzirá o seguinte resultado.

Selecione o local. Você verá o seguinte resultado.

Modificar home.xhtmlnovamente no diretório implantado onde você implantou o aplicativo conforme explicado abaixo. Mantenha o resto dos arquivos inalterados.

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>valueChangeListener Examples</h2>
      
      <h:form>    
         <h2>ValueChangeListener interface</h2>
         <hr/>
         <h:panelGrid columns = "2">
            Selected locale :
            <h:selectOneMenu value = "#{userData.selectedCountry}"
               onchange = "submit()">
               <f:valueChangeListener 
                  type = "com.tutorialspoint.test.LocaleChangeListener" />
               <f:selectItems value = "#{userData.countries}" />
            </h:selectOneMenu>
            Country Name: 		 
            <h:outputText id = "country1" value = "#{userData.selectedCountry}"
               size = "20" />		
         </h:panelGrid>
      </h:form>
   
   </h:body>
</html>

Quando estiver pronto com todas as alterações feitas, atualize a página no navegador. Se tudo estiver bem com sua aplicação, isso produzirá o seguinte resultado.

Selecione o local. Você verá o seguinte resultado.