JSF 2 actionListener example
In JSF, “Action Events” are fired by clicking on a button or link component, e.g h:commandButton or h:commandLink.
Do not confuse these two tags, actions is used to perform business logic and navigation task; While action listeners are used to perform UI interface logic or action invoke observation.
Common use case of this action listener is used to get back the attribute value that’s attached to a component, see this JSF 2 f:attribute example.
Here are two ways to implement it :
1. Method binding
In button or link component, you can specified a bean’s method directly in the “actionListener” attribute.
JSF page…
<?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:body> <h1>JSF 2 actionListener example</h1> <h:form id="form"> <h:commandButton id="submitButton" value="Submit" action="#{normal.outcome}" actionListener="#{normal.printIt}" /> </h:form> </h:body> </html>
Managed Bean…
The method which interacts action event should accept a ActionEvent parameter.
package com.mkyong; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ActionEvent; @ManagedBean(name="normal") @SessionScoped public class NormalBean{ public String buttonId; public void printIt(ActionEvent event){ //Get submit button id buttonId = event.getComponent().getClientId(); } public String outcome(){ return "result"; } }
2. ActionListener
In button or link component, add a “f:actionListener” tag inside, and specified an implementation class of ActionListener interface, and override its processAction().
JSF page…
<?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:body> <h1>JSF 2 actionListener example</h1> <h:form id="form"> <h:commandButton id="submitButton" value="Submit" action="#{normal.outcome}" > <f:actionListener type="com.mkyong.NormalActionListener" /> </h:commandButton> </h:form> </h:body> </html>
Implementation of ActionListener interface
package com.mkyong; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; public class NormalActionListener implements ActionListener{ @Override public void processAction(ActionEvent event) throws AbortProcessingException { System.out.println("Any use case here?"); } }








[...] JSF 2 action listener example Oracle Magazine – Free! [...]