@WebListener Annotation Example (Jakarta EE)

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this blog post, we'll explore the @WebListener annotation, which is used to declare a listener in a web application. A listener is an object that gets notified when certain events occur in a web application, such as when the application starts or stops, when a session is created or destroyed, and so on.

The @WebListener annotation is part of the Jakarta Servlet API and is used to annotate a class to declare it as a listener. This annotation eliminates the need to configure listeners in the web.xml file.

Step 1: Add Servlet Dependency to pom.xml

First, we need to add the Jakarta Servlet dependency to our pom.xml file. Here, we are using version 6.1.0.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.servlet.tutorial</groupId>
    <artifactId>java-servlet-tutorial</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>java-servlet-tutorial Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- Jakarta Servlet dependency -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>java-servlet-tutorial</finalName>
    </build>
</project>

Step 2: Create a Listener Using @WebListener

Let's create a simple listener that listens to context initialization and destruction events.

AppContextListener.java

package net.javaguides.servlet.tutorial.httpservlet;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Web application started");
        // Additional initialization code
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("Web application stopped");
        // Additional cleanup code
    }
}

In this example, the AppContextListener class implements the ServletContextListener interface and is annotated with @WebListener. The contextInitialized method is called when the web application is starting up, and the contextDestroyed method is called when the web application is shutting down.

Additional Examples of @WebListener

Session Listener

You can also create listeners for session events using the @WebListener annotation.

package net.javaguides.servlet.tutorial.httpservlet;

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;

@WebListener
public class AppSessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("Session created with ID: " + se.getSession().getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session destroyed with ID: " + se.getSession().getId());
    }
}

In this example, the AppSessionListener class implements the HttpSessionListener interface and is annotated with @WebListener. The sessionCreated method is called when a new session is created, and the sessionDestroyed method is called when a session is invalidated or timed out.

Commonly Used Listener Interfaces

  • ServletContextListener: Receives notification events about ServletContext lifecycle changes.
  • HttpSessionListener: Receives notification events about HTTP session lifecycle changes.
  • ServletRequestListener: Receives notification events about ServletRequest lifecycle changes.

Conclusion

In this blog post, we demonstrated the usage of the @WebListener annotation to declare listeners in a web application. We covered the basic usage and provided additional examples to illustrate how to create listeners for different types of events. The @WebListener annotation simplifies listener configuration by allowing listeners to be defined directly in the Java class.

References

Related Servlet Posts

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare