Home » Enterprise Java » jsf » JSF Actionlistener Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

JSF Actionlistener Example

JSF Event and Listener model are based on JavaBeans specification. In this example, we will learn how to setup jsf actionlistener with eclipse and tomcat. We will discuss the tools used and steps required to configure the application.
 
 
 
 
 
 
 
 

1. Introduction

Action listeners are provided to make it easier to handle action events. Java server faces already provides some event handling. For example, clicking a button or a hyperlink on a page causes an event to be called. However, that event handler is limited in what it can do because it has no access to the state of the user interface. They do receive information about the user interface and thus can be used for more robust event handling.

JSF fires action events when a user clicks on a button or link component like h:commandButton or h:commandLink etc. An action event is handled by 2 ways:

  1. Method Binding
  2. ActionListener Interface

1.1 Method Binding

In this, we use the managed bean method directly into actionListener attribute of the corresponding UI component

Bean Class:

@ManagedBean @SessionScoped
public class UserBeanData {
   public void bindingMessage(ActionEvent actionEvent) {
	 message = "JSF Action Listener Test - Using Method Binding.";
   }
}

Component:

<h:commandButton id="methodBindingBtn" value="Submit" actionListener="#{userBeanData.bindingMessage}" />

1.2 ActionListener Interface

In this, we create a class which implements this interface and override the processAction() method. Pass the class name into c:actionListener tag of the corresponding JSF component

Bean Class:

public class ActionListenerTest implements ActionListener {
    @Override
    public void processAction(ActionEvent actionEvent) throws AbortProcessingException { 
	  System.out.println("Calling Action Listener Usecase");
    }
}

Component:

<h:commandButton id="actionListenerBtn" value="Submit" action="#{userBeanData.showResult}">
	<c:actionListener type="com.jsf.tutorial.ActionListenerTest" />
</h:commandButton>

2. JSF Actionlistener Example

2.1 Tools Used

Our preferred environment is Eclipse. We are using Eclipse Kepler SR2, JDK 8 (1.8.0_131) and Tomcat 7 application server. Having said that, we have tested the code against JDK 1.7 and it works well

2.2 Project Structure

First, let’s review the final project structure in case you are confused about where you should create the corresponding files or folder later

jsf-actionlistener-application-project-structure

jsf-actionlistener-application-project-structure

2.3 Project Creation

In this section, we will see how to create a dynamic web project with Eclipse. In eclipse IDE, go to File -> New -> Dynamic web project

jsf-project-guide-2

fig. 1 – Create Dynamic Web Project

In the “New Dynamic Project” window fill in the below details and click next

  • Enter the project name and project location
  • Select “Target runtime” as “Apache Tomcat v7.0” from dropdown
  • Select “Configuration” as “JavaServer Faces v.2.2 Project from dropdown (this is required to download the java server faces capabilities in your project)
jsf-project-guide-3

fig. 2 – Project Details

Leave everything as default in this window (we will make the java files at a later stage). Simply click next and we will land up on the web-module window.

jsf-project-guide-9

fig. 3 – Java Src Window

In the Web Module window, leave the context_root and content_directory values as default. Simply, check “Generate web.xml deployment descriptor” checkbox and click next

jsf-project-guide-4

fig. 4 – Web Module Window

In the capabilities windows, we will require downloading the dependencies (not available by default) so that our project is configured as a faces module in eclipse. Add the capabilities to the web project by clicking on the download icon (encircled in fig. 5) and download the JSF 2.2 mojara implementation

jsf-project-guide-5

fig. 5 – JSF Capabilities Window

A new pop-up window will open where it will auto lists down the library. Select the JSF 2.2 library and click next (the library name and download destination will be auto populated)

jsf-project-guide-6

fig. 6 – JSF Capabilities Download Window

Check the license checkbox and click finish. Eclipse will download the library and will display them on the JSF capabilities windows (i.e. fig5)

jsf-project-guide-7

fig. 7 – JSF Capabilities License Window

Now the implementation libraries will be listed down on the capabilities page. Select the checkbox (JSF2.2 (Mojarra 2.2.0)) and leave everything else as default. Click finish

jsf-project-guide-8

fig. 8 – JSF Capabilities Library Selection Window

Eclipse will create the project in the workspace and web.xml will be configured for accepting the faces requests. It will have the following code.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JSF ActionListener1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

Now let’s start building the application!

2.4 Application Building

2.4.1 File Creation

For the demo, we will have an input file containing attribute and listener tag. Right click on project WebContent -> New -> File

Note – In JSF 2.0, it’s recommended to create a JSF page in xhtml format, a file format with a .xhtml extension

jsf-project-guide-10

fig. 9 – File Creation

A pop-up window will open, verify the parent folder location as JSF ActionListener/WebContent and enter the file name (input.xhtml) and click Finish

jsf-project-guide-11

fig. 10 – input.xhtml

Repeat the where we need to create the file for our application (i.e. fig. 9). Again, verify the parent folder location as JSF ActionListener/WebContent and enter the filename (output.xhtml) and click Finish.

jsf-project-guide-12

fig. 11 – output.xhtml

Now in order to use the rich UI components, we need to declare the below namespaces at top of the page in the prepared files

xmlns:c="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"

Here in the input.xhtml we will have the UI component’s for actionListener attribute and c:actionListener tag. The action attribute on the button will show the corresponding result. Add the following code to it –

input.xhtml

<!DOCTYPE HTML>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:c="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">
<h:head>
	<title>JSF Action Listener</title>
</h:head>
<h:body>
	<h2>JSF Action Listener Example</h2>
	<h:form>
		<h3>Method Binding</h3>
		<h:commandButton id="methodBindingBtn" value="Submit" action="#{userBeanData.showResult}" actionListener="#{userBeanData.bindingMessage}" />
		<br></br>
		<h3>ActionListener Interface</h3>
		<h:commandButton id="actionListenerBtn" value="Submit" action="#{userBeanData.showResult}">
			<c:actionListener type="com.jsf.tutorial.ActionListenerTest" />
		</h:commandButton>
	</h:form>
</h:body>
</html>

In the output page, JSF will display the output based on the actionlistener called in the input page. Add the following code to it –

output.xhtml

<!DOCTYPE HTML>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html">
<h:head>
	<title>JSF Action Listener</title>
</h:head>
<h:body>
	<h3>
		<h:outputText value="#{userBeanData.message}" />
	</h3>
</h:body>
</html>

2.4.2 Java Class Creation

Let’s create the required java files. Right click on src folder New -> Package

jsf-project-guide-13

fig. 11 – Java Package Creation

A new pop window will open where we will enter the package name, namely com.jsf.tutorial

jsf-project-guide-14

fig. 12 – Java Package Name

Once the package is created in the application, we will need to create the required managed bean and listener class. Right click on the new create package New -> Class

jsf-project-guide-15

fig. 13 – Java Class Creation

A new pop window will open and enter the file name as ActionListenerTest. The listener class will be created inside the package –  com.jsf.tutorial

jsf-project-guide-16

fig. 14 – ActionListenerTest.java

Repeat the step in fig.13 and enter the file name UserBeanData. Similar to above the managed bean class will also be created inside the package –  com.jsf.tutorial

jsf-project-guide-17

fig, 15 – UserBeanData.java

2.4.3 Managed Bean & Implementation of ActionListener interface

UserBeanData.java

This class has a method which interacts with action event and accepts an ActionEvent parameter

package com.jsf.tutorial;

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

@ManagedBean @SessionScoped
public class UserBeanData {
	private String message = "JSF Listeners";
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public void bindingMessage(ActionEvent actionEvent) {
		message = "JSF Action Listener Test - Using Method Binding.";
	}
	public String showResult() {
		return "output";
	}
}

ActionListenerTest.java

In button component, we have added a c:actionListener tag. This tag has its implementation class which will implement the ActionListener interface and overrides it’s processAction()

package com.jsf.tutorial;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

public class ActionListenerTest implements ActionListener {
	@Override
	public void processAction(ActionEvent actionEvent) throws AbortProcessingException { 
		System.out.println("Calling Action Listener Usecase");
		UserBeanData userBeanObj = (UserBeanData) FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("userBeanData"); 
		userBeanObj.setMessage("JSF Action Listener Test - Using 'c:actionListener'"); 
	} 
}

2.5 Project Deploy

Once we are ready with all the changes done, let us compile and deploy the application on tomcat7 server. In order to deploy the application on tomcat7, right-click on the project and navigate to Run as -> Run on Server

jsf-tomcat-deploy-18

fig. 1 – How To Deploy Application On Tomcat

Tomcat will deploy the application in its webapps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser

jsf-tomcat-deploy-19

fig. 2 – Tomcat Processing

Open your favorite browser and hit the following URL. The output page will be displayed

http://localhost:8085/JSF_ActionListener/faces/input.xhtml

Server name (localhost) and port (8085) may vary as per your tomcat configuration

2.6 Project Demo

When we will hit the application url, the output page will be displayed

demo-fig. 1 – Output Page

demo-fig. 1 – Output Page

Click Submit button for Method binding

demo-fig. 1 – Method Binding

demo-fig. 1 – Method Binding Output

Click Submit button for ActionListener Interface

demo-fig. 1 – ActionListener Interface

demo-fig. 1 – ActionListener Interface

Hope this helped :)

3. Conclusion

Through this example, we have learned on how to configure the actionlisteners in eclipse and deploy it using the tomcat7 application server

4. Download the Eclipse Project

This was a JSF listeners example with Eclipse and Tomcat

Download
You can download the full source code of this example here: JSF ActionListener
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of