Thursday, 18 April 2013

JSF ActionListener Example

JSF ActionListener

In JSF when user interacts with GUI components like h:commandButton or h:link, the JSF triggers an action events
these events can be implemented in two ways.

1. Method binding- Create a method in managed bean and call this via actionListener attributes
2. Using ActionListener interface- Create a separate class which implements ActionListener and implement processAction method.

1.Create  a managed bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

@ManagedBean(name = "actionListenerBean", eager = true)
public class ActionListenerBean {
    public ActionListenerBean() {
        System.out.println("My ActionListenerBean");

    private String name;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String submit() {
        System.out.println("submit clicked");
        return "success.jsp";
    public void actionSubmit(ActionEvent e) {
        System.out.println("Action submit triggered");
        System.out.println("Action submit event =" + e.getComponent().getId());


2. Create an Action listener class which implements ActionListener

package com.vinod.jsf;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
public class MyActionListener implements ActionListener {
    public void processAction(ActionEvent event) throws AbortProcessingException {
        System.out.println("Executing process action event   "+event.getComponent().getId());


3. Create xhtml file to create ui components

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
<title>My JSF Examples</title>
            <h:outputText value="Hello ActionListener!" />
        <h:outputText id="name" value="Name :" />
        <h:inputText id="nametext" value="#{}">
        <h:outputText value="ActionListener Using method binding" />
        <h:commandButton value="Method binding 1" id="methodbindingButton1"
            action="#{actionListenerBean.submit}" />
        <br> </br>
        <br> </br>
        <h:outputText value="ActionListener Using ActionListener Interface" />
        <h:commandButton id="ActionListenerButton"
            value="Action Listener Interface"
            <f:actionListener type="com.vinod.jsf.MyActionListener" />


4. Run it..

5. Done !! example (vinod-jsf)