Defining a session listener for a J2EE Web Application


First, I created a new java class called SessionListener, after that implemented the HttpSessionListener interface for listening HttpSessionEvent raised by the Application Server.

package com.project.listeners;

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

public class SessionListener implements HttpSessionListener {

 public void sessionCreated(HttpSessionEvent arg0) {
//called by the app. Server whenever a new session is created
  System.out.println(“New session is created!!”);
  
 }

 public void sessionDestroyed(HttpSessionEvent arg0) {
//called by the app. Server whenever a session is destroyed
  System.out.println(“Session is destroyed!!”);
  
 }

Second, I have edited web.xml file to define the listener class inside the application.

<?xml version=”1.0″ encoding=”UTF-8″?>
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:jsp=”http://java.sun.com/xml/ns/javaee/jsp” xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” id=”WebApp_ID” version=”2.5″>
        <display-name>ApacheProject</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>
        <listener>
            <listener-class>com.project.listeners.SessionListener</listener-class>
        </listener>
    </web-app>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s