Java Servlet @WebListener Annotation Example
- Details
- Written by Nam Ha Minh
- Last Updated on 26 June 2019   |   Print Email
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:
- javax.servlet.ServletContextListener
- javax.servlet.ServletContextAttributeListener
- javax.servlet.ServletRequestListener
- javax.servlet.ServletRequestAttributeListener
- javax.servlet.http.HttpSessionListener
- javax.servlet.http.HttpSessionAttributeListener
Syntax of @WebListener Annotation:
@WebListener([optional description])
Attributes of @WebListener Annotation:
Name | Type | Required | Description |
value | String | Optional | Description of the listener. |
Some Examples with @WebListener Annotation:
- The following example code uses the @WebListenerannotation to register a class as a listener for the ServletContextListener’s events:
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"); } }
- The following example code registers a listener which implements two interfaces with description:
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.
Related Java Servlet Annotations:
- @WebServlet annotation
- @WebFilter annotation
- @WebInitParam annotation
- @HandlesTypes annotation
- @MultipartConfig annotation
- @ServletSecurity, @HttpMethodContraint and @HttpConstraint annotations
Other Java Servlet Tutorials:
- Java Servlet Quick Start for beginners (XML)
- Java Servlet for beginners (annotations)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- Handling HTML form data with Java Servlet
- Java File Download Servlet Example
Comments