Load on Startup Servlet Example

Load on Startup 

 

The <load-on-startup> tag which is present inside the <servlet> tag helps you to control when the servlet has to be loaded by the Container. This load-on-startup tag information present in the web.xml helps the container to load the mentioned servlets as soon as the servlet container starts.

If you don’t specify the load-on-startup tag, container will load the servlet whenever the first request comes from the particular servlet only.

    <servlet>

              <servlet-name>TestServlet</servlet-name>

              <servlet-class>com.ivv.test.TestServlet</servlet-class>

              <load-on-startup>1</load-on-startup>

       </servlet>

If there are multiple servlets are there and each servlet has load-on-startup information, then container will load the servlets based on its value. Web container loads the Servlets with lower load-on-startup value first compared to the servlets with higher values

     <servlet>

              <servlet-name>TestServlet</servlet-name>

              <servlet-class>com.ivv.test.TestServlet</servlet-class>

              <load-on-startup>1</load-on-startup>

       </servlet>

      <servlet>

      <servlet-name>SecondServlet</servlet-name>

              <servlet-class>com.ivv.test.SecondServlet</servlet-class>

              <load-on-startup>2</load-on-startup>

       </servlet>

load on startup

load on startup

Here TestServlet will be loaded first by web container as its load-on-startup value is lower compared to others and followed by SecondServlet.

Important Points regarding <load-on-startup>

  • Web container loads the Servlets with lower load-on-startup value first compared to the servlets with higher values.
  • If two or more servlets have same load-on-startup value, then they will be loaded in the order on which they declared in the web.xml.
  • <load-on-startup> value can be either 0 or positive or negative.
  • If the value is 0 or negative or unspecified, container will decide when that particular servlet has to be loaded.
  • <load-on-startup> will guarantees loading, initialization i.e. calling init() method of servlet by the container.

In which scenario we need to use load-on-startup?

 As discussed, load-on-startup tag’s value will decide when the particular servlet has to be loaded by the container and lower the load-on-startup value will be loaded first. Based on business requirements select the jobs such as downloading files, parsing the files, creating database connection, pre loading the data into memory etc. which will consume more time.

If any servlet preforming these kind of jobs declare their load-on-startup value based on the requirement so that these jobs will be loaded first once web container starts which will reduce the response time of web application.

Leave a Reply

Your email address will not be published. Required fields are marked *