Nishant123
Nishant123

Reputation: 1966

How to add a Listener programatically for Servlets?

In Servlet 3.0 there is a way to add listeners programatically in ServletContextListener's contextInitialized() method. Servlets and Filters can be added programatically as below (please correct the below code if I am wrong)

public void contextInitialized(ServletContextEvent sce) {

        ServletContext sc = sce.getServletContext();

        // Register Servlet
        ServletRegistration sr = sc.addServlet("DynamicServlet",
            "com.sample.DynamicServlet");
        sr.setInitParameter("servletInitName", "servletInitValue");
        sr.addMapping("/dynamic");

// Register Filter
FilterRegistration fr = sc.addFilter("DynamicFilter","com.sample.TestFilter");
fr.setInitParameter("filterInitName", "filterInitValue");
fr.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST),
                                     true, "DynamicServlet");
    }

Likewise, I was hoping if anyone could share an example of adding a Listener programatically as I don't know how to do it.

Also is it possible to add ServletContextListener itself programatically? If yes, then where should I add it?. As all the Servlets, Listeners, Filter's and their instantiation is done from contextInitialized() method. So if I have to instantiate it programatically where should I declare it?

Thanks in Advance

Upvotes: 1

Views: 2850

Answers (1)

wero
wero

Reputation: 33010

You can add a ServletContextListener programmatically since Servlet 3.0, by calling ServletContext.addListener(Class<? extends EventListener>).

However this can only be done from ServletContainerInitializer.onStartup which is run before any ServletContextListeners are called.


The Javadoc of ServletContext.addListener(Class<? extends EventListener>) reads:

Adds a listener of the given class type to this ServletContext.
The given listenerClass must implement one or more of the following interfaces:

ServletContextAttributeListener
ServletRequestListener
ServletRequestAttributeListener
HttpSessionAttributeListener
HttpSessionIdListener
HttpSessionListener 

If this ServletContext was passed to ServletContainerInitializer.onStartup(...), then the given listenerClass may also implement ServletContextListener, in addition to the interfaces listed above.

Upvotes: 1

Related Questions