HttpSessionBindingListener Example

Note

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

Here we are using @WebListener annotation

HttpSessionBindingListenerExample.java

package com.listener;

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

@WebListener
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());
   
}
}

ListenerServletExample.java

package com.listener;

import java.io.IOException;
import java.io.PrintWriter;

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
*/

@WebServlet("/ListenerServletExample")
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()));
       session.removeAttribute
("name");

      
       PrintWriter out = response.getWriter
();
       out.append
("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 *