Java EE >> Servlets >> Web Applications
What is preinitialization of a java servlet?
Loading Servlets on Startup
When the web server is being started, the servlets are not loaded by default. All the servlets configured in a Java EE web application are loaded when the first time they are accessed. This means that first time a request comes to a servlet, it is loaded (instantiated) and the init() method of servlet is invoked.
For some applications, this becomes a bottleneck because there could be a lot of initialization code written inside the init() method of a servlet including the creation of Connection Pool, Caching, File Handler Pool or Thread Pool. Thus the first request will have to wait until all the initialization is complete. This could become more worse if there are more requests coming from users immediately after the first request. In that case, all other requests will block until the servlet has been initialized by the init() method.
In order to avoid the kind of situation described above, one can per-initialize the servlets. All modern day web and application servers support the functionality of preloading the servlets. To preinitialize a servlet the deployment descriptor for that servlet should include the load on startup tag with some integer to specify the loading order. Thus a servlet with load on startup value as 1 will be loaded before a servlet with load-on-startup value of 2. The following web.xml snippet shows how to use the load-on-startup tag for per-initialization of servlets:
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>com.example.MyServlet1</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>com.example.MyServlet2</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
The following points should be noted while using the load-on-startup tag or using preloading of servlets:
- <0 means=”" that=”" the=”" servlet=”" is=”" instantiated=”" at=”" sole=”" discretion=”" of=”" server=”" which=”" could=”" be=”" during=”" startup=”" or=”" after=”" receiving=”" first=”" request=”" for=”" li=”">
- >=0 means that the servlet container will load servlets in the increasing order of the values for load-on-startup tag.
- 0 is also a valid value of load-on-startup tag and signifies the highest priority for loading servlets during server startup
- If 2 or more servlets have the same value for load-on-startup, then the order of the servlets declared in the web.xml decides which servlet will get loaded first during server startup
Other Java EE Tutorials
Is Struts2 Obsolete
Which Framework to Use for Java MVC Web Applications
How to write Rich Internet Applications
Force Page to Login Page after Session Timeout in Struts2


