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:

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment