public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { // perform actions when ServletContext is initialized } public void contextDestroyed(ServletContextEvent event) { // perform actions when ServletContext is destroyed } } // Registering the listener in web.xmlcom.example.MyServletContextListener
public class MyAttributeListener implements ServletContextAttributeListener { public void attributeAdded(ServletContextAttributeEvent event) { // perform actions when an attribute is added } public void attributeRemoved(ServletContextAttributeEvent event) { // perform actions when an attribute is removed } public void attributeReplaced(ServletContextAttributeEvent event) { // perform actions when an attribute is replaced } } // Adding the listener to the ServletContext ServletContext context = getServletContext(); context.addListener(new MyAttributeListener()); // Removing the listener from the ServletContext context.removePListener(new MyAttributeListener());Package library: javax.servlet