By default Servlet is not loaded until servlet container receives a request for the particular servlet. This may cause a delay in accessing the servlet for the first time. To avoid the delay in access time, you can use <load-on-startup> tag in your web.xml file that allows you to force the servlet container to load (instantiated and have its init() called) the servlet as soon as the server starts.
How to use <load-on-startup>?
Here is a sample web.xml file:
<web-app> … <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.beginnersbook.DemoServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> … </web-app>
If I didn’t specify the <load-on-startup>, the web container would not have loaded the servlet until it receives a request for DemoServlet servlet class. Since I have specified a value >=0, this servlet (DemoServlet class) would be loaded on the startup.
value >= 0 means that the servlet is loaded when the web-app is deployed or when the server starts, if the value < 0 then servlet would be loaded whenever the container feels like.
How to specify the order of servlet loading using <load-on-startup> tag?
<web-app> … <servlet> <servlet-name>MyServlet1</servlet-name> <servlet-class>com.beginnersbook.DemoServlet1</servlet-class> <load-on-startup>5</load-on-startup> </servlet> <servlet> <servlet-name>MyServlet2</servlet-name> <servlet-class>com.beginnersbook.DemoServlet2</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet> <servlet-name>MyServlet3</servlet-name> <servlet-class>com.beginnersbook.DemoServlet3</servlet-class> <load-on-startup>-2</load-on-startup> </servlet> … </web-app>
In this example we have three Servlets specified in the web.xml file, since servlet classes DemoServlet1 and DemoServlet2 has load-on-startup value >=0, they both will be loaded as soon as the server starts. However servlet class DemoServlet2 would be loaded before the DemoServlet1 class because it has lower load-on-startup value.
Servlet class DemoServlet3 would not be loaded on startup as it has negative load-on-startup value.
Leave a Reply