Search code examples
javajspsession-state

How do I run a method in the session event Onclose/onDestroy?


I working with JSP.
I need run a method in ever session closing, i.e., whenever the browser is closed.
how do I make this?


Solution

  • On server-side you can register an HttpSessionListener:

    package com.example
    public class MySessionListener implements HttpSessionListener {
    
        public void sessionCreated(HttpSessionEvent event) {
            System.out.println("Session created");
        }
    
        public void sessionDestroyed(HttpSessionEvent event) {
            System.out.println("Session destroyed");
        }
    }
    

    To register you can either add @WebListener annotation to the listner's class or add the listener to web.xml

    <listener>
        <listener-class>com.example.MySessionListener</listener-class>
    </listener>
    

    The listener won't be called in the moment when the browser is closed it will be called when the session is timed out.