Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • HttpSessionAttributeListeners in Servlet

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 344
    Comment on it

    In Servlet we can also track the events using the Listeners, In below code script we have to track the events using the listeners. we have easily maintained the HttpSession events with the HttpSessionAttributeListener while we add, remove or replace the HttpSession attributes.

    MyListener.java

    package com.evon.listeners;
    
    import javax.servlet.http.HttpSessionAttributeListener;
    import javax.servlet.http.HttpSessionBindingEvent;
    
    public class MyListener implements HttpSessionAttributeListener {
    
        @Override
        public void attributeAdd(HttpSessionBindingEvent event) {
            String attributeName = event.getName();
            Object attributeValue = event.getValue();
            System.out.println("Attribute added : " + attributeName + " : " + attributeValue);
        }
    
        @Override
        public void attributeRemove(HttpSessionBindingEvent event) {
            String attributeName = event.getName();
            Object attributeValue = event.getValue();
            System.out.println("Attribute removed : " + attributeName + " : " + attributeValue);
        }
    
        @Override
        public void attributeReplace(HttpSessionBindingEvent event) {
            String attributeName = event.getName();
            Object attributeValue = event.getValue();
            System.out.println("Attribute replaced : " + attributeName + " : " + attributeValue);   
        }
    }
    

    Then insert the entry of your listener class inside the web.xml file.

    web.xml

    <web-app ...>
            <listener>
            <listener-class>com.evon.listeners.MyAttributeListener</listener-class>
        </listener>
    </web-app>
    

    Then you have to call the below statements from your code.

      HttpSession session = request.getSession();
      session.setAttribute("name", "manish");      //attributeAdd() is call
      session.setAttribute("name", "mahi"); //attributeReplace() is call
      session.removeAttribute("name"); //attributeRemove() is call
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: