Servlets give you more when it comes to this issue. And in Java world, events are called listeners. There are some useful listeners:
javax.servlet.ServletContextListener
void contextDestroyed(ServletContextEvent sce)
Called when the servlet context is about to be destroyed.
void contextInitialized(ServletContextEvent sce)
Called when the web application is ready to process requests.
javax.servlet.ServletContextAttributeListener
void attributeAdded(ServletContextAttributeEvent scae)
Called when a new attribute is added to the servlet context.
void attributeRemoved(ServletContextAttributeEvent scae)
Called when an attribute is removed from the servlet context.
void attributeReplaced(ServletContextAttributeEvent scae)
Called when an attribute on the servlet contextis replaced.
javax.servlet.http.HttpSessionListener
void sessionCreated(HttpSessionEvent se)
Called when a session is created.
void sessionDestroyed(HttpSessionEvent se)
Called when a session is invalidated.
javax.servlet.http.HttpSessionAttributeListener
void attributeAdded(HttpSessionBindingEvent se)
Called when an attribute is added to a session.
void attributeRemoved(HttpSessionBindingEvent se)
Called when an attribute is removed from a session.
void attributeReplaced(HttpSessionBindingEvent se)
Called when an attribute is replaced in a session.