Session Listener Example

Session Listener Example

Posted in : Servlet Posted on : June 21, 2011 at 1:14 PM Comments : [ 0 ]

This section contains detail about Session Listener implementation in java.

Session Listener Example

Listener is predefined interface available in life cycle of application. Session Listener deals with the session object. For HTTP session events, the event listener classes can receive notification when an HTTP session is activated or is about to be deactivated, and when an HTTP session attribute is added, removed, or replaced.

Example Class)

package j2ee;

import javax.servlet.http.*;
import javax.servlet.http.HttpSessionListener;

public class ListenerSession implements HttpSessionListener {
public ListenerSession() {

public void sessionCreated(HttpSessionEvent sessionEvent) {
// Get the session that was created
HttpSession session = sessionEvent.getSession();
// Store something in the session, and log a message
try {
System.out.println("Session created: " + session);
session.setAttribute("dog", "labrador");
session.setAttribute("name", "Diana");
} catch (Exception e) {
System.out.println("Error in setting session attribute: "
+ e.getMessage());

public void sessionDestroyed(HttpSessionEvent sessionEvent) {
// Get the session that was invalidated
HttpSession session = sessionEvent.getSession();
// Log a message
System.out.println("Session invalidated: " + session);
System.out.println("The breed of the dog is: "
+ session.getAttribute("dog"));
System.out.println("The name of the dog is : "
+ session.getAttribute("name"));

package j2ee;

import javax.servlet.*;
import javax.servlet.http.*;

public class ServletListenerSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
String str = (String) session.getAttribute("dog");
String dogName = (String) session.getAttribute("name");
pw.println("The breed of the dog is " + str);
pw.println("The name of the dog is " + dogName);


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
id="WebApp_ID" version="2.5">


When you execute the following code, you will get the following output :

In console you will get the following message :


Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics