Table of contents
1.
Introduction
2.
JSF
3.
Method to handle value change event
3.1.
Method Binding
3.2.
Bean class
3.3.
JSF component
3.4.
ValueChangeListener Interface
3.5.
Java class
3.6.
JSF component
4.
Example
4.1.
UserData.java
4.2.
LocaleChangeListener.java
4.3.
home.xhtml
4.4.
home.xhtml
5.
Frequently Asked Questions
5.1.
Describe the process for calling multiple listeners in JSF.
5.2.
What use does the Controller module serve?
5.3.
What function does the View module serve?
5.4.
What is a listener class?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

JSF valueChangeListener

Author Ayush Mishra
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello, Ninja! Have you ever found a situation where you needed to interact with user input components? You will run across issues while designing websites where interaction with input is necessary. JSF has valueChangeListener for event handling.

You will discover JSF Custom Converter in this blog. Let's get going!

JSF

JSF (Java Server Faces) is a framework for creating client-side user interfaces. It was created using the Java programming language, has a component-based design, and offers common management capabilities for these components. It has a large number of advanced tag libraries and sophisticated APIs.

Component provision and state management fall under the purview of the APIs. Data transformations, extensibility, accessibility, and server-side validation are all made simpler. Adding components to web pages and connecting them to backend objects is made simpler by tag libraries. For applying component tags, it has handles.

Method to handle value change event

The JSF fires a valueChangeEvent, which may be handled in one of two ways when the user interacts with input components like h:inputText or h:selectOneMenu.

1. Method Binding.

2. ValueChangeListener Interface.

Method Binding

In the valueChangeListener property of the appropriate JSF component, use the managed bean method directly.

Bean class

@ManagedBean(name="testBean")
@SessionScoped
public class TestBean{ 
public void valueChangeMethod(ValueChangeEvent e){
//method body
} 
}

JSF component

<h:selectOneMenu value="#{testBean.property}" onchange="submit()"
valueChangeListener="#{testBean.valueChangeMethod}">
    <f:selectItems value="#{testBean.testValues}" />
</h:selectOneMenu>

ValueChangeListener Interface

Implement the ValueChangeListener interface and supply the implementation class name to the UI component's valueChangeListener property.

Java class

public class ValueListenerTestClass implements ValueChangeListener{ 
@Override
public void processValueChange(ValueChangeEvent event)
throws AbortProcessingException { 
//method body 
}
}

JSF component

<h:selectOneMenu value="#{testBean.property}" onchange="submit()">
    <f:valueChangeListener type=" ValueListenerTestClass" />
    <f:selectItems value="#{testBean.testValues}" />
</h:selectOneMenu>

Example

To evaluate the valueChangeListener in JSF, let's build a test JSF application.

Step 1: reate a project named HelloWorld under the package com.codingNinjas.test.

Step 2: UserData.java should be modified as described below.

Step 3: Create the file LocaleChangeListener.java in the comcodingNinjas.test package. Change it as described below.

Step 4: Make the changes outlined below to home.xhtml. Leave the remaining files alone.

Step 5: To ensure that the business logic operates by the requirements, compile and execute the application.

Step 6: Create the program as a war file, then deploy it to the Apache Tomcat Webserver.

Step 7: Launch your web application using the proper URL as described in the last step below.

UserData.java

package com.codingNinjas.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.codingNinjas.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>

 

Let's build and execute the application after you finish all the modifications. This will result in the following outcome if everything with your application is in order.

Select locale. The outcome will be as follows.

Modify home.xhtml again in the deployed directory where you've deployed the application, as explained below. Keep the rest of the files unchanged.

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>

 

Refresh the page in your browser after you are through with all the changes. This will result in the following outcome if everything with your application is in order.

Select locale. The outcome will be as follows.

Frequently Asked Questions

Describe the process for calling multiple listeners in JSF.

JSF tags for "value change listeners" and "action listeners" may attach one or more listeners to an element to call multiple listeners.

What use does the Controller module serve?

It manages an application's processing.

What function does the View module serve?

This module displays the interface.

What is a listener class?

A listener class is a class that is connected to an event. For instance, if the event is a valueChange event, the ValueChangeListener listener class is connected to it.

Conclusion

Finally, you have reached the article's conclusion. Congratulations!! You gained knowledge of JSF's valueChangeListener in this blog. You looked at the method to handle value change events and examples to change the value.

Are you eager to read more articles on JSF? Coding Ninjas cover you, so don't worry. View the JSF to learn more.

Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!

Live masterclass