3

I have to create a class that implements ServletContextListener to add an event during the initialization or the shutdown of Tomcat. However, the class has to be located in a jar file inside WEB-INF/lib. After doing some readings, I found out that this is not possible, and the alternative is to use ServletContainerInitializer. However, only onStartup() method is available.

Is there any other alternatives where I can also add an event during the shutdown or destruction of the web application?

I am using Tomcat 8 and Java 8 btw.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
r051cky
  • 115
  • 4

2 Answers2

5

Let your ServletContainerInitializer programmatically add a ServletContextListener which in turn does the desired job in its contextDestroyed().

servletContext.addListener(YourServletContextListener.class);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
-1

Not sure how you tested your code. But this the ServletContextListener works fine for me on Tomcat 8.5.5. Just try this code, no need to put this to separate JAR file.

@WebListener
public class AppContextListener implements ServletContextListener{

    Logger log = LoggerFactory.getLogger(AppContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        log.info("### Context is destroyed ###");
    }
}
RadekSohlich
  • 182
  • 1
  • 3
  • 11
  • Actually I though r051cky can't use the separate jar to include the ServletContainerInitializer implementation. The configuration in web.xml could be used. com.example.AppContextListener – RadekSohlich Oct 03 '16 at 07:44
  • No need to argue with you. I prefer to know what my application do. – RadekSohlich Oct 03 '16 at 07:54
  • To be honest currently working on Tapestry projects, which is the bunch of magic. But you are true, the Spring especially Spring Boot uses all of these too. And you are right that is very, very comfortable to use. But if you are going to do anything very custom, you are in big pain and headache sometimes. :) – RadekSohlich Oct 03 '16 at 08:06