HttpSessionAttributeListener 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

HttpSessionAttributeListenerExample.java

package com.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class HttpSessionAttributeListenerExample implements  HttpSessionAttributeListener {

 
@Override
 
public void attributeAdded(HttpSessionBindingEvent event) {
   
String attributeName = event.getName();
    Object attributeValue = event.getValue
();
    System.out.println
("Attribute added : " + attributeName + " : "  + attributeValue);
 
}

 
@Override
 
public void attributeRemoved(HttpSessionBindingEvent event) {
   
String attributeName = event.getName();
    Object attributeValue = event.getValue
();
    System.out.println
("Attribute removed : " + attributeName + " : "+ attributeValue);
 
}

 
@Override
 
public void attributeReplaced(HttpSessionBindingEvent event) {
   
String attributeName = event.getName();
    Object attributeValue = event.getValue
();
    System.out.println
("Attribute replaced : " + attributeName + " : "+ attributeValue);
 
}
}

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();
    
//When new session attribute is created then attributeAdded() is executed
    
session.setAttribute("url", "javatips.net");
    
//When session attribute is replaced then attributeReplaced() is executed
    
session.setAttribute("url", "javatips.net");
    
//When session attribute removed then attributeRemoved() is executed
    
session.removeAttribute("url");
      
       PrintWriter out = response.getWriter
();
       out.append
("Session Created Successfully");
   
}
}

Tomcat Console Output

Attribute added : url : javatips.net
Attribute replaced : url : javatips.net
Attribute removed : url : javatips.net




Previous 1 2








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