Skip to content
Related Articles

Related Articles

Working of Servlet

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 28 Feb, 2022

A Servlet is an instance of a class that implements javax.servlet.Servlet. Most Servlets, however, are extended to one of the standard implementations of that interface, as it namely javax.servlet.GenericServlet and the javax.servlet.http.HttpServlet. Developers use this as a blueprint when crafting their Servlets code. Implementing the Servlet’s interface or extending the GenericServlet/HttpServlet class provides a framework for creating a Servlet as well as significant default functionality to it. The Servlet’s code spec must override at least one method when any custom functionality is being implemented. 

In order to initialize the Servlet, the Web server:

  • Loads the Servlet class [and probably other classes which are referenced by the Servlet] and creates an instance by calling the no-arguments constructor
  • Calls the Servlet’s init( ServletConfig config). init() is called only once when the Servlet is loaded in memory for the first time and stored in the ServletConfig object. The Servlet creator can encapsulate any code that must run before the main code spec of the Servlet is executed such as connecting to a database for instance. The ServletConfig object supplies the Servlets with info about its initializing parameters. These parameters are given to the Servlet itself and are not associated with any single request. The ServletConfig object can be retrieved by calling a Servlet’s getServletConfig(), and This is handled by GenericServlet

Any Java-enabled Web server automatically invokes the Servlet’s service() in response to a client request. This means when a Servlet is initialized, its service ( ServletRequest request, ServletResponse response) is called for every request to the Servlet. Hence, service() must be overridden to provide customized functionality the moment a Servlet is invoked. However, if the Servlet developer chooses not to override the service(), there are other methods that can be invoked in response to a client’s request to it. When the Servlet needs to be unloaded, for example, because a new version should be loaded or the server is shutting down, destroy() is called. Based on this brief Explanation, a skeleton of a common Servlet has been constructed. For simplicity, A skeleton of Servlet that follows does not include parameters passed to its methods are or exception handling code for any exceptions that are thrown:


pubic dass SkeletonServet extends HttpServiet
    public void init()
        // Initialization code goes here 
    pubicvoid service()
        // Meaningful work happens here 
    public void destroy() 
        // Free resources here  

Every Servlet engine must adhere to the Servlet lifecycle.


In order to initialize the Servlet, the Servlet engine firstly locates its class. A Servlet class can reside on the local file system, and a remote file system or be on some other network resource. The Servlet’s engine uses a usual Java class to load facilities to load the Servlet class into the JVM. Once loaded, the Servlet engine instantiates an instance of that servlet class [and the other classes which are referenced by the Servlet]. After that, it will be Calls Servlet init(ServletConfig config). The init() is called immediately after the Servers constructs the Servlet’s instance. Thus, Depending on the server and its configuration, this can be called at any of such following cases:

  • When the Server starts
  • When the Servlet is first requested, Then  just before service() is invoked
  • At the request of the server administrator

The init() Method

init() is declared as follows:

public void init(ServletConfig config) throws ServletException

During initialization, the Servlet has to access two objects:

  • ServletConfig
  • ServletContext

This is because to init() an object of ServletConfig is passed as a parameter. When a Servlet is set up for the first time, the configuration data such as information about the parameters and references to the ServletContext is stored in the ServletConfig object. The Following the common tasks that can be implemented by overriding init() of Servlet interface:

  • Reading initializing parameters using ServletConfig object
  • Reading the configuration data from the persistent resources like a configuration file
  • When Initializing a database driver, then a connection pool or a logging service
  • Opening a JDBC connection
  • Writing log information to a network resource

A Servlet that cannot complete its initialization process throws UnavailableException, Thus, Only after the completion of Initialization, will the server be ready for the client requests to handle [ i.e. before service() is called] or a Servlet is destroyed.


After the server loads and initializes a Servlet, Then the Servlet is able to handle the client requests. It processes them into service(). Each client’s request to service) is run in separate at Servlet thread. service() is declared as follows:

public void service(ServletRequest request, ServletResponse response)

The Method public void service(ServletRequest request, ServletResponse response) throws ServletException And IOException. For, every request to the Servlet, its service() is called. Two objects i.e. ServletRequest and The ServletResponse are passed as parameters to the service(). the ServletRequest object helps in accessing the original request data and The ServletResponse object provides methods that will help the Servlet to build a response.

Servlets can run multiple service() at a time. It is important, therefore, hence that service() has been written in a thread-safe manner. For example, if service() updates some crucial data in the Servlet object, access to this thread should be synchronized. if for some reason, the server should not run another service() concurrently, the Servlet should implement SingleThreadModel. This interface guarantees that no two threads will execute the Servlet’s service() concurrently.


When instructed to unload the Servlet Thus, perhaps by the server’s administrator or programmatically by the Servlet’s to itself, the Servlet engine calls the Servlets to destroy(). The Servlet is then eligible for the garbage collection. All resources which were allocated in the init() should be released in a destroy(). destroy() is declared as follows:

public void destroy()

The method is run once. The server will not be run it again until after it reloads and reinitializes the Servlet. The common tasks implemented in destroy() are:

  • Synchronizing cleanup tasks such as closing any open resources, closing a connection pool
  • Informing another application that Servlet will no longer be in the service

destroy() is guaranteed to be called only once during the Servlet’s lifecycle. During a Servlet’s lifecycle, it is important to write thread-safe code for destroying the Servlet, and unless the Servlet implements SingleThreadModel, servicing client requests. There may still be threads that execute service() when destroy() is called, so destroy() has to be thread-safe. These steps illustrate the entire lifecycle of a Servlet and are also diagrammatically represented as shown in Diagram 1.

Lifecycle of a Servlet

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!