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.
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.
精彩评论