Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a java class (not a servlet) when the tomcat server starts [duplicate]

I need to continuously update and query a mysql database (and I don't think I need a servlet to do this, just a regular java class). But I don't know how to call that class or run it when the servlet starts.

like image 233
Kirn Avatar asked Nov 14 '10 01:11

Kirn


1 Answers

Let that class implement ServletContextListener. Then you can do your thing in contextInitialized() method.

public class Config implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        // Webapp startup.
    }

    public void contextDestroyed(ServletContextEvent event) {
        // Webapp shutdown.
    }

}

Register it in web.xml as follows to get it to run:

<listener>
    <listener-class>com.example.Config</listener-class>
</listener>

Or if you're already on Servlet 3.0, then just use @WebListener annotation on the class.

like image 83
BalusC Avatar answered Sep 29 '22 19:09

BalusC