Life Cycle of Servlet in Java

Life Cycle of Servlet in Java. Various activities that happen from the birth to death of an object are called the life cycle. Important activities of the life-cycle are called life-cycle events. For example, the life cycle events in the Human life cycle are:- birth, the start of schooling, end of schooling, getting Job, marriage, retirement, death.

The Servlet life cycle means keeping track of all the operations from servlet class object creation to destruction. Executing logic for the life cycle event is called event handling. 

Servlet Life Cycle Events

The servlet life cycle events are:-

  1. Servlet Instantiation Event:- It raises when servlet container creates servlet class object. This event raises only once for a servlet component.
  2. Request Processing Event:- It raises when the servlet container keeps the servlet class object ready to process the request. This event raises for each and every request.
  3. Destruction Event:- It raises when the servlet container is about to destroy a servlet class object. This event also raises only once for a servlet component.

The method that will be executed by servlet container for servlet life-cycle events is called servlet life cycle methods or container callback methods.

Servlet Life Cycle Methods

To handle the servlet life cycle events three important methods will be called by the servlet container. The methods for the Life Cycle of Servlet are:-

Servlet Life Cycle EventsServlet Life Cycle Methods
Servlet Instantiation Eventinit(-) method
Request Processing Eventservice(-,-) method
Destruction Eventdestroy(-) method

init(-) Method

Servlet life cycle method for Instantiation Event:- init(-) method. Method Signature:- 

public void init(ServletConfig cg) throws ServletException

  • It is a one-time executing block of servlet components.
  • We can override this method in the servlet component class having initialization logic like creating a JDBC connection with database software.
  • There are two init methods are given in servlet API:- init(), and init(ServletConfig cg) method. Among them, only the init(ServletConfig cg) method is the life cycle method. The init() method which doesn’t contain any parameter is given as a convenience method for the programmer (i.e. use only when required).

Servlet Container creates a ServletConfig object on one per servlet class object. Servlet Container creates this object and handovers it to the servlet class object. We can use the ServletConfig object to pass information to the Servlet component and to gather details about the servlet component.

service(-,-) Method

Servlet life cycle method for Request Processing Event:- service(-,-) method. Method Signature:- 

public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException

  • Once servlet component instantiation and initialization are completed and it is ready to process then this request processing event will be raised. For this event service(-,-) method declared in Servlet(I) will be executed. 
  • The request processing event is a repeatedly executing event of the servlet component life cycle. It executes in every request. Hence, we place request processing logic or business logic in the service(-,-) method.
  • There are two service(-,-) methods are available in Servlet API:- public void service(ServletRequest req, ServletResponse resp) and protected void service(HttpServletRequest req, HttpServletResponse resp) method. Among them only public service(ServletRequest req, ServletResponse resp) is a life cycle method. 
  • The protected service(HttpServletRequest req, HttpServletResponse resp) method and 7 doXxx(-) method of HttpServlet class are not part of the life cycle method. They are called through life cycle method service(ServletRequest req, ServletResponse resp) directly or indirectly by the servlet container.

destroy() Method

Servlet life cycle method for Destruction Event:- destroy() method. Method signature:-

public void destroy()

  • When the servlet container is about to destroy a servlet component class object, then the destruction event will be raised and the destroy() method will be executed as part of the servlet life cycle method.
  • It is also a one-time executing block of servlet components.
  • We can override this method to keep deinitialization logic like closing the JDBC connection and releasing non-Java resources (connection to database, file, and e.t.c.) from the servlet component.

Servlet container is giving servlet life cycle methods to programmers for two reasons,

a) To override servlet life cycle methods to place programmer choice logic in servlet components. So that programmer’s written logic can execute even though the entire life cycle of the servlet component is taken care by the servlet container.

b) To get access to servlet container created objects in our servlet component as the parameters of servlet life cycle methods like ServletConfig obj of init(-) method, ServletRequest and ServletResponse objects of service(-,-) method.

Notes

  • Servlet Container doesn’t use init(-) method logic to create our servlet class object. It is having its own internal logic to create our servlet class object. Therefore we can use the init(-) method for writing our choice initialization logic.
  • Servlet Container doesn’t use destroy() method logic to destroy the servlet class object. It has its own internal logic to destroy the servlet class object. Therefore we can use destroy() method for writing our choice uninitialization logics.
  • The web container or servlet container does not use JVM’s garbage collector to destroy our servlet class objects, it will use its own garbage collector for this purpose because sometimes servlet containers need to destroy servlet class objects even though it is in utilization forcefully when required. But JVM garbage collectors can destroy the objects only when they are completely free or idle having no reference.
  • The Servlet container doesn’t use the “new” operator to create a servlet class object. The servlet class name will be collected from the web.xml file dynamically at runtime and the object will be created at runtime through Reflection API. 

How are Servlet Life Cycle Methods called?

In servlet architecture and workflow we discussed in detail how servlet containers are performing different operations on servlet components. Now, let us see what happens when 1st request is given to the servlet component with respect to the servlet life cycle methods.

  1. The Servlet container creates one set of ServletRequest and ServletResponse objects for the current request.
  2. Servlet container loads Servlet class from WEB-INF/classes folder and instantiates that object by using 0-param constructor. Example:- Class.forName(“com.kp.servlet.DateServlet”).newInstance();
  3. The Servlet container raises an instantiation event and calls init(ServletConfig cg) method on our servlet class object. Here the ServletConfig object will be assigned to our servlet class object.
  4. Servlet container calls start/create one thread representing the current request and raise “request processing event”.
  5. Servlet container calls service(ServletRequest req, ServletResponse resp) method on our servlet class object.
  6. The service(-,-) method sends the generated output to the browser through the response object and web server.
  7. The Servlet container destroys the thread that is created for the current request.
  8. It also destroys the ServletRequest, ServletResponse objects of the current request.

What happens when the servlet container gets other than the 1st request from the browser?

  • The Servlet container creates one set of ServletRequest and ServletResponse objects for the current request.
  • Servlet container checks the availability of servlet class objects.
  • If not available, then treat it as the first request. If available then the servlet container locates that object and performs the only 6th to 8th steps of the first request.

Servlet Program to Demonstrate Life Cycle of Servlet, Events, and Methods

The HTMl file (index.html),

<h1>Servlet Life Cycle</h1>
<h2><a href="test">Get Current Date and Time</a></h2>

The servlet component (LifeCycleTestServlet.java),

package com.kp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServlet;

public class LifeCycleTestServlet extends HttpServlet {
   static {
      System.out.println("LifeCycleTestServlet: staic block");
   }
   public LifeCycleTestServlet() {
      System.out.println("LifeCycleTestServlet: 0-param Constructor");
   }
   @Override
   public void init(ServletConfig config) throws ServletException {
      System.out.println("LifeCycleTestServlet: init(-) method");
   }
   @Override
   public void service(ServletRequest req, ServletResponse resp) 
         throws ServletException, IOException {
      System.out.println("LifeCycleTestServlet: service(-,-) method");
      // set response content type
      resp.setContentType("text/html");
      // get Writer
      PrintWriter pw = resp.getWriter();
      // write response
      pw.println("<h1>Current Date and Time: "+
                 new Date() + "</h1>");
      // link to home
      pw.println("<h3><a href='index.html'>Home</a></h3>");
      // close stream
      pw.close();
   }
   @Override
   public void destroy() {
      System.out.println("LifeCycleTestServlet: destroy() method");
   }
}

The deployment descriptor (web.xml) file,

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xsi:schemaLocation=
  "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  id="WebApp_ID" version="4.0">
  <display-name>LifeCycleTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html </welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>lifecycle</servlet-name>
    <servlet-class>com.kp.servlet.LifeCycleTestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>lifecycle</servlet-name>
    <url-pattern>/test</url-pattern>
  </servlet-mapping>
</web-app>

See the source code of the above web application (developed in Eclipse) at GitHub.

The HTML file index.html is configured as a welcome file list, therefore by default index.html page will come after starting the server. Now, we give requests to servlet components through a hyperlink on index.html. Due to the first request, we get the following output on the console:-

LifeCycleTestServlet: static block
LifeCycleTestServlet: 0-param Constructor
LifeCycleTestServlet: init(-) method
LifeCycleTestServlet: service(-,-) method

Now, for every next request (refresh) only the service(-,-) method is called, and we following output on the console:-

LifeCycleTestServlet: service(-,-) method

In this process, the destruction event will not be raised, and therefore the destroy() method will never be called by the servlet container. When we restart the server or stop the server then destruction event will be raised and we will get the following output on the console:-

LifeCycleTestServlet: destroy() method

FAQ

Q1) What happens if we call destroy() method from the service(-,-) method?
Servlet class objects will not be destroyed but the logics of destroy() method executes along with service(-,-) method logics. When the life cycle events are raised then the servlet container calls the related method itself, but we already called the life cycle method manually therefore the life cycle event will not be raised by the servlet container.

Q2) What happens if we call the init(-) method from the service(-,-) method?
The logic of the init(-) method also executes from the service(-,-) method but new objects for the servlet component class will not be created.

Q3) What happens if we call destroy() method from the init(-) method?
The logic of destroy() method will be executed along with the init(-) method.

Q4) What happens if the main(-) method is placed in the servlet component?
The Servlet container executes the servlet component through life cycle methods. Since the main(-) method is not a life cycle method therefore it will not be executed as part of the servlet life cycle. It will be executed only if it is called explicitly from any servlet life cycle method, else it will be treated as a normal ordinary method with no use.

Q5) How is the servlet component executing without the main(-) method?

The standalone application begins the execution by calling the main(-,-) main method. Since the servlet component is not a standalone application and it is a web component of the web application, therefore there is no need of having a main(-) method.

Servlet container executes our servlet component through the life cycle method since main(-) is not the life cycle method of servlet component therefore there is no need of placing the main(-) method in our servlet component.

JVM starts the webserver by calling the main(-) method. This main(-) creates a servlet container and the servlet container manages the given servlet component life cycle through life cycle methods. Therefore the main(-) method is not required in servlet containers and also in servlet components. The main(-) method will be there only in the class that starts the webserver. 

In tomcat server that class name is org.apache.catalina.startup.Bootstrap. Go to <Tomcat_home>\bin\bootstrap.jar file, from META-INF/MANIFEST.MF which contains “Main-Class: org.apache.catalina.startup.Bootstrap”. This Bootstrap class contains the main method. This main(-) method creates a servlet container (Catalina) and that servlet container manages the given servlet component life cycle through life cycle methods. 

We can get the Bootstrap.class file from bootstrap.jar\org\apache\catalina\startup, and we can use any Java decompiler to convert the .class file to .java file or see this decompiled Bootstrap.java.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.