JSF 2.2 valueChangeListener Attribute Example
Usually Components in Web application are dependent on each other. To keep dependent component in sync, it is possible to change the dependent component on change of independent component.Example: Say we have input form where we have two inputs Select Country select menu and State text box. Now if selected country is say USA, State label is ok but if country is JAPAN we should change label to Prefecture (Prefecture corresponds to State in Japan). So to perform such kind of changes we can use valueChangeListener.
valueChangeListener can be implemented in two ways
- valueChangeListener attribute (this example explains this way)
- <f:valueChangeListener> tag
Note! valueChangeListener attribute and <f:valueChangeListener> tag has following subtle differences
- valueChangeListener attribute can be bound to managed bean method, while <f:valueChangeListener> tag can be bound to class that implements ValueChangeListener interface
- valueChangeListener attribute allows to attach only single managed bean method to component, while <f:valueChangeListener> tags can be used to attach multiple listeners to component
Code Snippet of valueChangeListener
To implement valueChangeListener, in xhtml file- add valueChangeListener=”#{bean.method}” attribute to input HTML element
- add onchange=”submit()” attribute to input HTML element. This invokes javascript submit function, when selected menu item is changed.
1
2
3
4
5
6
|
<h:selectOneMenu id="countryList"
value="#{indexBean.selectedCountry}"
onchange="submit()"
valueChangeListener="#{indexBean.onCountrySelect}">
<f:selectItems value="#{indexBean.countries}" />
</h:selectOneMenu>
|
JSF 2.2 valueChangeListener attribute Example
In this example, form containing Select Country select menu and State text box is displayed. The label for State text box is changed based on Country selected. i.e. State is displayed for USA and Prefecture is displayed for Japan.JSF 2.2 JAR Dependency
- javax.faces-2.2.4.jar
- jsf-api-2.2.4.jar
Development Environment
- JDK 1.7.0_07
- Tomcat v7.0
- JSF 2.2
- Eclipse 4.2
index.xhtml
Displays input form with Select Country select one menu and State input text box. Based on country selected, state label is changed by use of valueChangeListenerIndexBean.java
Managed Bean class with onCountrySelect() method that is bound to valueChangeListener. onCountrySelect() sets the state label based on selected state.web.xml
Project Layout
Example Output
Input Page
As you can in following Output Page, when Japan is selected as country,
valueChangeListener method is invoked, which sets State label to
Prefecture and hence Prefecture is displayed
Output Page
Logoutput is as follows
1
2
3
4
|
---- initialize ----
----- onCountrySelect method -----
***** oldValue: null
***** newValue: JAPAN
|
Comments
Post a Comment