Truong Van Hoc
Truong Van Hoc

Reputation: 87

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?

Upvotes: 1

Views: 668

Answers (1)

Guillaume Barré
Guillaume Barré

Reputation: 4218

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>

Upvotes: 3

Related Questions