Domino & REST: Listeners for Initialization & Destroying of a Servlet

If you need to know when your Servlet is initialized or destroyed, you can use a ServletContextListener in your application.

First, create the class AppServletContextListener and implement the javax.servlet.ServletContextListener interface. This provides two methods for capturing the events: contextInitialized and contextDestroyed:

package ch.hasselba.servlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AppServletContextListener
               implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("ServletContextListener started");
    }
}

The ServletContextEvent allows you to access the ServletContext if required.

Now you have to register the listener in your web.xml:

<web-app>
     <listener>
         <listener-class>
             ch.hasselba.servlet.AppServletContextListener
         </listener-class>
    </listener>
</web-app>

As soon as you start or stop the HTTP task, the Listener is called, and you can execute some application specific code (i.e. shutdown threads, bring out the garbage, etc.)

Dieser Beitrag wurde unter Java, JEE, REST, Server abgelegt und mit , , , , , verschlagwortet. Setze ein Lesezeichen auf den Permalink.

2 Kommentare zu Domino & REST: Listeners for Initialization & Destroying of a Servlet

  1. Slade Swan sagt:

    Hi Sven,
    Thanks for documenting this information. I have followed a combination of what you have put here together with your „Domino & REST: A Basic Servlet“ together with a semi-unrelated StackOverflow response by Paul Withers (https://stackoverflow.com/questions/33808182/deploying-osgi-servlet-to-domino-ibm-presentation-404-error) in an attempt to get a HTTP Servlet (as opposed to a REST based servlet) to run any code upon start-up of the Domino http server. However, I can’t get the your example to fire on startup and I must be doing something wrong. The „ServletContextListener started“ from your above example only displays after the first http get request to the servlet not at http startup.
    I’m hoping to convert an existing servlet to an OSGi plugin with the promise of enterprise deployment through Domino’s toolbox.nsf with policies etc.
    Would there be any assistance or pointers you could provide?
    Thanks in advance.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.