jsf

JSF Httpsessionlistener Example

Hello, in this tutorial we will study about the HttpSessionListener in a jsf enabled application and will demonstrate the following:

  • Login form
  • Validating the login credentials in a managed bean and creating the session id based on the successful user authentication
  • Displaying the result page and performing application logout (thereby, destroying the created session id)

This example will show how to implement and integrate the HTTP session listener in jsf.

1. Introduction

The listener is one of the most popular technologies used in the J2EE web application. It is part of the Java Servlet as defined in Servlet 2.3 but they have their own specific functionalities. There are two most widely used Servlet Listeners i.e. ServletContextListener and HttpSessionListener

There are multiple sessions that are related to listeners, for e.g.

ListenerDescription
HttpSessionActivationListenerLet’s you know when a session moves from one virtual machine to another
HttpSessionBindingListenerLet’s your attribute class object get notified when they are added or removed from session
HttpSessionAttributeListenerLet’s you know when any attribute is added, removed or replaced in a session

 

In this tutorial, we will have the following components in our application:

  • login.xhtml – A jsf page having bootstrap enabled login form with jsf components
  • success.xhtml – If the login is successful, it will show the logged in username
  • Login Bean – Managed bean class to handle user’s login & logout requests and invoke the corresponding HttpSessionListener methods
  • SessionCounterListener – A HttpSessionListener class to listen to session events
  • web.xml – Web application configuration file

But before we create the application let’s take a look at the session listener utility in jsf.

1.1 HttpSessionListener

The HttpSessionListener interface receives notifications of changes to list the active sessions in a web application and perform some action. It is used to perform some important tasks and monitor when sessions are created and destroyed. For e.g. – counting the number of active sessions, maintain a log of user details such as login time, logout time etc. Its best practical use would be to track session use statistics for a server.

The HttpSessionEvent class gives notifications for changes to sessions within a web application.

1.2 Why is HttpSessionListener needed?

We may have a requirement to receive a notification whenever a new session is created or we would like to know how many sessions are active on the website so that we can know how many users are logged in and active on the website.

1.3 Methods of HttpSessionListener Interface

There are two methods declared in the HttpSessionListener interface which must be implemented by the servlet programmer to perform some action,

MethodsDescription
public void sessionCreated(HttpSessionEvent event)This method receives a notification whenever a session is created
public void sessionDestroyed(HttpSessionEvent event)This method receives a notification whenever a session is destroyed

1.4 How can it be achieved?

To receive notification events, the implementation class must be configured in the deployment descriptor (i.e. web.xml) for the web application. This entry points the server to a class that will be called when a session is created or destroyed.

The entry required is simple. All we need is a listener and listener-class element in the below format:

Sample web.xml

<listener>
	<listener-class>com.samplepackage.MySessionListener</listener-class>
</listener>

Note: The listener-class element must be a fully qualified class name.

Now, open up the Eclipse IDE and let’s start building the application!

2. JSF HttpSessionListener Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 (1.8.0_131), Tomcat7 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!

Fig. 1: Jsf HttpSessionListener Application Project Structure
Fig. 1: Jsf HttpSessionListener Application Project Structure

2.3 Project Creation

The below example shows how to implement session listener in an application. With the implementation of HttpSessionListener interface, developers will be notified of changes to the list of active sessions in a web application.

This section will demonstrate on how to create a Dynamic Web Java project with Eclipse. In Eclipse IDE, go to File -> New -> Dynamic web project

Fig. 2: Create Dynamic Web Project
Fig. 2: 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)

Fig. 3: Project Details
Fig. 3: Project Details

Leave everything as default in this window as we will be making the required java file at a later stage. Simply click next and we will land up on the web-module window

Fig. 4: Java Src Window
Fig. 4: Java Src Window

In the Web Module window, leave the context_root and content_directory values as default (however, you can change the context_root but for the first application let’s keep it as a default value). Simply, check Generate web.xml deployment descriptor checkbox and click next

Fig. 5: Web Module Window
Fig. 5: Web Module Window

In the JSF Capabilities windows, we will require downloading the dependencies (not available by default) so that our project is configured as a JSF module in Eclipse. Add the JSF capabilities to the web project by clicking on the download icon (encircled in Fig. 6) and download the JSF 2.2 Mojarra implementation

Fig. 6: JSF Capabilities Window
Fig. 6: JSF Capabilities Window

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

Fig. 7: JSF Capabilities Download Window
Fig. 7: JSF Capabilities Download Window

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

Fig. 8: JSF Capabilities License Window
Fig. 8: JSF Capabilities License Window

Now the JSF 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

Fig. 9: JSF Capabilities Library Selection Window
Fig. 9: JSF Capabilities Library Selection Window

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

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 HttpSessionListener</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, we need to configure the HttpSessionListener in web.xml so that application knows about this. In your web.xml add the below code just above the </web-app> tag,

HttpSessionListener Configuration Code

  <listener>
	<listener-class>com.jsf.httpsessionlistener.SessionCounterListener</listener-class>
  </listener>

Let’s start building the application!

3. Application Building

Following are the steps involved in developing this application.

3.1 Source File Creation

For the demo, we will have an output file displaying the products list. 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 .xhtml extension

Fig. 10: File Creation
Fig. 10: File Creation

A pop-up window will open. Verify the parent folder location as JSF HttpSessionListener/WebContent and enter the file name as login.xhtml. Click Finish.

Fig. 11: login.xhtml
Fig. 11: login.xhtml

Repeat the step listed in Fig. 10 and verify the parent folder location as JSF HttpSessionListener/WebContent and enter the file name as success.xhtml and click Finish

Fig. 12: success.xhtml
Fig. 12: success.xhtml

3.1.1 Implementation of Input & Output file

Here in the login.xhtml, we will have the form based UI components. The action attribute on the button will show the result based on the logic written in the managed-bean. Add the following code to it:

login.xhtml

<!DOCTYPE HTML>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" http-equiv="X-UA-Conpatible" />
    <h:outputStylesheet library="css" name="bootstrap.min.css" />
    <title>JSF HttpSessionListener</title>
    <style type="text/css">
    	.formPosition {
    		width: 40%;    		
    		margin: 24px;
    	}
    	.errorMsg {
    		color: red;
    		padding-top: 16px;  		
    	}
    </style>
</h:head>
<h:body>
    <center><h2>JSF HttpSessionListener Example</h2></center>
    <div class="container">
        <div class="row">
            <div class="form_bg">
                <h:form id="loginForm" styleClass="formPosition">
                    <div class="form-group">
                        <h:outputLabel value="Username " />
                        <h:inputText id="loginName" value="#{loginBean.loginName}" styleClass="form-control" />
                    </div>
                    <div class="form-group">
                        <h:outputLabel value="password" />
                        <h:inputSecret id="loginPassword" value="#{loginBean.loginPassword}" styleClass="form-control" />
                    </div>
                    <div>
                    	<h:commandButton value="Login" action="#{loginBean.doApplicationLoginLogout}" styleClass="btn btn-primary">
                    		<f:param name="operation" value="login" />
                    	</h:commandButton>
                    </div>
                    <div class="errorMsg"><h:message for="loginName" /></div>
                </h:form>
            </div>
        </div>
    </div>
</h:body>
</html>

If the authentication is successful, a user will be shown on the success page and a new session will be created. This page will have a logout button to invalidate the session. Add the following code to it:

success.xhtml

<!DOCTYPE HTML>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1" http-equiv="X-UA-Conpatible" />
    <h:outputStylesheet library="css" name="bootstrap.min.css" />
    <title>JSF HttpSessionListener Example</title>
</h:head>
<h:body>
    <center><h2>JSF HttpSessionListener Example</h2></center>
    <div class="container">
        <div class="row">
            <div class="form_bg">
            	Welcome <h:outputLabel value="#{loginBean.loginName}" />
            	<div id="logoutBtn">
            		<h:form id="logoutForm">
            			<h:commandButton value="Logout" action="#{loginBean.doApplicationLoginLogout}" styleClass="btn btn-primary">
                    		<f:param name="operation" value="logout" />
						</h:commandButton> 
            		</h:form>            		
            	</div>           	
            </div>
        </div>
    </div>
</h:body>
</html>

3.2 Java Class Creation

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

Fig. 13: Java Package Creation
Fig. 13: Java Package Creation

A new pop window will open where we will enter the package name as com.jsf.httpsessionlistener

Fig. 14: Java Package Name (com.jsf.httpsessionlistener)
Fig. 14: Java Package Name (com.jsf.httpsessionlistener)

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

Fig. 15: Java Class Creation
Fig. 15: Java Class Creation

A new pop window will open and enter the file name as LoginBean. The managed bean class will be created inside the package com.jsf.httpsessionlistener

Fig. 16: Java Class (LoginBean.java)
Fig. 16: Java Class (LoginBean.java)

Repeat the step listed in Fig. 15, and enter the file name as SessionCounterListener. The listener class will be created inside the package com.jsf.httpsessionlistener

Fig. 17: Java Class (SessionCounterListener.java)
Fig. 17: Java Class (SessionCounterListener.java)

3.2.1 Implementation of Managed Bean

This class has getters & setters and doApplicationLoginLogout()method to handle the user’s application login & logout operations. Add the following code to it:

LoginBean.java

package com.jsf.httpsessionlistener;

import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean @RequestScoped
public class LoginBean {

	private String loginName;
	private String loginPassword;
	private static HttpSession sessionObj;

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getLoginPassword() {
		return loginPassword;
	}

	public void setLoginPassword(String loginPassword) {
		this.loginPassword = loginPassword;
	}
	
	public String doApplicationLoginLogout() {	
		String appResponse = "";				
		Map<String,String> parameterValue = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		if(parameterValue.get("operation").equals("login")) {
			System.out.println("Entered Username?= " + loginName + ", Password?= " + loginPassword);
			if(loginName.equalsIgnoreCase("javacodegeek") && loginPassword.equals("access123")) {
				appResponse = "success";							
				sessionObj = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);				
			}
			else {
				appResponse = "login";
				FacesContext.getCurrentInstance().addMessage("loginForm:loginName", new FacesMessage("Username Or Password Is Incorrect"));				
			}
		} else {			
			sessionObj.invalidate();			
			appResponse = "login";
		}
		return appResponse;
	}
}

3.2.2 Implementation of Listener Class

Whenever a session is created or destroyed the managed bean will invoke this class. In this example, sessionCreated() and sessionDestroyed() methods will be invoked based on the application’s login and logout scenario respectively. Add the following code to it:

SessionCounterListener.java

package com.jsf.httpsessionlistener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounterListener implements HttpSessionListener {

	private static int activeSessionCount;

	public static int getActiveSessionCount() {
		return activeSessionCount;
	}

	@Override
	public void sessionCreated(HttpSessionEvent createObj) {
		activeSessionCount++;
		createObj.getSession().setAttribute("SessionCount", activeSessionCount);
		System.out.println("Session Created For Id?= " + createObj.getSession().getId());			
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent destroyObj) {
		activeSessionCount--;
		System.out.println("Session Destroyed For Id?= " + destroyObj.getSession().getId());
	}
}

4. 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

Fig. 18: How to Deploy Application On Tomcat
Fig. 18: How to Deploy Application On Tomcat

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

Fig. 19: Tomcat Processing
Fig. 19: Tomcat Processing

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

http://localhost:8082/JSFHttpSessionListener/faces/login.xhtml

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

5. Project Demo

Now, we are done with the application and it’s time to test out the application. When we will hit the testing url, you will see the application’s login form page

Fig. 20: Application Login Page
Fig. 20: Application Login Page

Enter username and password (test / test@123) there and click Login. You will see an error message saying “Username or Password Is Incorrect”

Fig. 21: Invalid Credentials Error Page
Fig. 21: Invalid Credentials Error Page

Again, enter the username and password (javacodegeek / access123) there and click Login. User will see a welcome message with Logout button and a corresponding session id for the user will be created

Fig. 22: Successful Application Login
Fig. 22: Successful Application Login

Clicking the Logout button will invalidate the session and you can confirm this from the output in Eclipse console

Fig. 23: Console Output
Fig. 23: Console Output

Hope this helped :)

6. Conclusion

Through this example, we have learned about the HttpSessionListener implementation in jsf. We have also deployed it using the Tomcat7 application server.

7. Download the Eclipse Project

This was a JSF HttpSessionListener example with Eclipse and Tomcat

Download
You can download the full source code of this example here: JSF HttpSessionListener

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
George
George
1 year ago

very nice tutorial … I am going to give it a try using wildfly

Back to top button