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.
Asked
Active
Viewed 3,711 times
1 Answers
17
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.

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
@BalusC, I've seen Tomcat do delayed loading. Will this run immediately or does this require a request to trigger loading? – Joshua Martell Nov 14 '10 at 01:48
-
No, this doesn't require a request. You probably had JSP's in mind. – BalusC Nov 14 '10 at 01:48
-
One question though, what does the @Weblistener annotation do? – Kirn Nov 16 '10 at 00:42
-
1It removes the need to register the listener in `web.xml`. Servlet 3.0 provides a bunch of annotations (`@WebListener`, `@WebFilter`, `@WebServlet`, etc) which makes the `web.xml` (almost) completely obsolete for registering listeners, filters and servlets. You can then even run your webapp without `web.xml` or with a very minimal one. – BalusC Nov 16 '10 at 00:44
-
Oh wow! That's so awesome. Double thank you!!! – Kirn Nov 16 '10 at 00:49
-
Annotations are definitely awesome :) – BalusC Nov 16 '10 at 00:51