Sometimes, when developing a web application, you need to automatically load a user's class after Tomcat starts and execute some initialization methods, such as loading the business dictionary from the database to the memory, therefore, you need to automatically load a class or run a class method at Tomcat startup. You can add a listener (servletcontextlistener configuration item) in the WEB-INF/Web. XML as follows:
1) added a listener myservletcontextlistener. Java to implement the javax. servlet. servletcontextlistener interface.
Package test. startup;
Import javax. servlet. servletcontextevent;
Import javax. servlet. servletcontextlistener;
Public class myservletcontextlistener implements servletcontextlistener
{
Public void contextdestroyed (servletcontextevent arg0)
{
}
Public void contextinitialized (servletcontextevent arg0)
{
System. Out. println ("load business Dictionary ");
Try
{
Com. EOS. Common. dict. dictmap. loaddata ();
}
Catch (exception E)
{
System. Out. println ("failed to load business dictionary! ");
E. printstacktrace ();
}
}
}
2) configure the listener web. xml:
<Listener>
<Listener-class> test. startup. myservletcontextlistener </listener-class>
</Listener>
Note: The Application Event listener is a notification class when the servlet environment or session object is created or modified. These are new content in servlet Specification Version 2.3. Registering a listener involves placing a listener element in the Web-app element of Web. xml. Although the structure of the listener element is simple, do not forget that the sequence of child elements in the Web-app element must be correctly given. The listener element is located before all servlet elements and after all filter-mapping elements. In addition, because the application lifetime listener is a new content in Serlvet Standard Version 2.3, you must use Version 2.3 or later of the web. xml dtd instead of Version 2.2, as shown below:
<Web-app id = "webapp_id" version = "2.4"
Xmlns = "http://java.sun.com/xml/ns/j2ee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
...
</Web-app>