开发者

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

This question already has an answer here: Using special auto start servlet to initialize on startup and share application data (1 answer) 开发者_运维百科 Closed 7 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜