Search code examples
javaspring-mvctriggerstomcat8

Trigger function when start running Tomcat


On Eclipse(Java), when I click Run Tomcat8 , I want to log the time to inform when did the server start to run. I don't know how to trigger this logging action since I have to access a page to call the log function in controller file. Is there anyway that I can write a log file whenever I start running Tomcat8?


Solution

  • If you want to do this without any Spring or Tomcat specificity and have a solution runnable on all kind of Java EE applications you can create a class implementing javax.servlet.ServletContextListener and get a notification that the web application is ready to process request in the method contextInitialized(ServletContextEvent sce).

    This method will be called when the application is deployed on the server.

    package com.your.package;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class YourServletContextListener implements ServletContextListener {
    
        public void contextInitialized(ServletContextEvent event) {
            // Place here the code to run once the application is ready 
        }
    
        public void contextDestroyed(ServletContextEvent event) {
            // Place here the code to run just before the application goes down
        }
    
    }
    

    This listener needs to be configured into your web.xml as follows

    </web-app ...>
      <listener>
        <listener-class>com.your.package.YourServletContextListener</listener-class>
      </listener>
    </web-app>