The @WebListener annotation is used to register a class as a listener of a web application. The annotated class must implement one or more of the following interfaces:
@WebListener([optional description])
Name | Type | Required | Description |
value | String | Optional | Description of the listener. |
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class ContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent event) { System.out.println("The application started"); } @Override public void contextDestroyed(ServletContextEvent event) { System.out.println("The application stopped"); } }
import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionListener; @WebListener("Session listener for the application") public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener { // overrides required methods here... }
A great application of using @WebListener is to implement hit counter for Java web applications. Read this tutorial to learn more.