Wednesday, October 8, 2025
HomeLanguagesJavaServlet – Load on startup

Servlet – Load on startup

The element ‘load-on-startup‘ is used to load the servlet. The ‘void init()‘ method of servlet gets executed when the server gets started. The element content of ‘load-on-startup’ is Integer.

  • if the integer is negative:  The container loads servlet at any time.
  • if the integer is 0 or positive: The servlet marked with lower integers are loaded before servlets marked with higher integers.

How to add element load-on-startup while mapping servlet?

The load-on-startup is the sub-attribute of servlet attribute in web.xml. We do mapping of servlet in web.xml file.

In XML file

XML




<servlet>
    <servlet-name>servletOne</servlet-name>
    <servlet-class>com.gfg.ServletOne</servlet-class>
    <load-on-startup>0</load-on-startup>  
</servlet>
  
<servlet>
    <servlet-name>servletTwo</servlet-name>
    <servlet-class>com.gfg.ServletTwo</servlet-class>
    <load-on-startup>1</load-on-startup>  
</servlet>


ServletOne load first then ServletTwo get load.

Servlet Code

servletOne.java

Java




package com.gfg;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
  
public class ServletOne extends HttpServlet
{
    public void init()
    {
        // this method will get execute
        // when the server get start
        System.out.println("ServletOne got called");
    }
}


servletTwo.java

Java




package com.gfg;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
  
public class ServletTwo extends HttpServlet
{
    public void init()
    {
         // this method will get execute 
        // when the server get start
        System.out.println("ServletTwo got called");
    }
}


Note: the above code is server-side code it will not work on online IDE (it is only for the clarification of the topic).

RELATED ARTICLES

Most Popular

Dominic
32342 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6712 POSTS0 COMMENTS
Nicole Veronica
11875 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6833 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6786 POSTS0 COMMENTS
Umr Jansen
6789 POSTS0 COMMENTS