I want the servlet container to load one or more servlets when the container is first fired up, as opposed to when a client issues a request for the servlets. How do I do that under Servlet 2.2 API?
Suppose you have two servlets, TestServlet_1 and TestServlet_2, that you'd like to get automatically loaded in when the servlet container is first fired up. And let's say that you want TestServlet_2 to be loaded before TestServlet_1. The following web.xml file placed in the WEB-INF directory of the relevant webapp would do the job.
<?xml version="1.0"?> <!DOCTYPE web-app SYSTEM "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <servlet> <servlet-class> TestServlet_1 </servlet-class> <load-on-startup> 5 </load-on-startup> </servlet> <servlet> <servlet-class> TestServlet_2 </servlet-class> <load-on-startup> 1 </load-on-startup> </servlet> </web-app>The optional content of the load-on-startup element, the positive integer 5 for TestServlet_1 and 1 for TestServlet_2, controls the order in which such servlets would be loaded into the container at startup. The smaller the value of the integer, which must be positive (even 0 is not allowed) to enable automatic loading at startup, the earlier the servlet would be loaded. If no value is specified or if the value specified is not a positive integer, the Tomcat 3.1 container will load the servlet only when a request is received for the servlet.
Getting a servlet container to load a servlet at startup can be very useful in certain applications, as for example pointed out by Alex Chaffee in a servlet FAQ posting.