Wednesday, April 8, 2020

Servlet @WebListener annotation

Servlet @WebListener annotation

The @WebListener annotation is applied to annotate a listener to the Servlet component. This annotation is available since Servlet 3.0.

@WebListener is annotated to declare a WebListener. Any Servlet Component using @WebListener must implement one or more of then one interface listed below;

  • javax.servlet.ServletContextListener
  • javax.servlet.ServletContextAttributeListener
  • javax.servlet.ServletRequestListener
  • javax.servlet.ServletRequestAttributeListener
  • javax.servlet.HttpSessionListener
  • javax.servlet. HttpSessionAttributeListener
  • javax.servlet. HttpSessionIdListener

@WebListener has only one attribute, the value of type String.



Example


import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(        
           initParams = {
           @WebInitParam(name = "author_name", value = "Pushpendra")
     },
    urlPatterns = {
     "/DemoServlet",
           "/WebServletAnnotation"
     }
)
@WebListener(value="Listener value")
public class DemoServlet extends HttpServlet implements ServletContextListener, ServletContextAttributeListener{
     private static final long serialVersionUID = 1L;
      
    public DemoServlet() {
        super();
    }
   
     @Override
     public void contextDestroyed(ServletContextEvent sce) {
           System.out.println("Destroyed");
           }

     @Override
     public void contextInitialized(ServletContextEvent sce) {
           System.out.println("Context Initialized");
     }

     @Override
     public void attributeAdded(ServletContextAttributeEvent scae) {
           System.out.println("Attribute added");
           }

     @Override
     public void attributeRemoved(ServletContextAttributeEvent scae) {
           System.out.println("Attribute removed");
          
     }

     @Override
     public void attributeReplaced(ServletContextAttributeEvent scae) {
           System.out.println("Attribute replaced");
          
     }
    
}


Result

@WebListener