HttpSessionBindingListener Example


From Servlet API 3.0, we can use javax.servlet.annotation, so that web.xml is not necessary

Here we are using @WebListener annotation

package com.listener;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

public class HttpSessionBindingListenerExample implements HttpSessionBindingListener {
ServletContext context;

public HttpSessionBindingListenerExample() {


public HttpSessionBindingListenerExample(ServletContext context) {
this.context = context;

public void valueBound(HttpSessionBindingEvent event) {
System.out.println("The value bound is " + event.getName());

public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("The value unbound is " + event.getName());

package com.listener;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

* This servlet is used for showing an example about sessionListener

public class ListenerServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(); //sessionCreated() method is invoked
session.setAttribute("name",new HttpSessionBindingListenerExample(getServletContext()));

       PrintWriter out = response.getWriter
("Session Created Successfully");

Tomcat Console Output

The value bound is name
The value unbound is name


Previous 1 2

Your email address will not be published. Required fields are marked *