Back to: Java Servlets Tutorials
Java Servlet Life Cycle
In this article, I am going to discuss the Servlet Life Cycle in Java. Please read our previous article where we discussed HTTP Servlet in Java with an example. At the end of this article, you will understand the following pointers.
- Understanding Servlet Life Cycle
- General Structure of a Simple User-Defined Servlet
- Instantiation phase of a Servlet
- How is the Servlet Container loading and Instantiating the Servlet?
- Initialization Phase of a Servlet
- Servicing Phase of a Servlet
- Destruction Phase of the Servlet
- Servlet Life Cycle Methods
Servlet Life Cycle:
The Servlet container controls the life cycle of a user-defined servlet. The Servlet life cycle is described by four life cycle phases and three life cycle methods. The Life cycle methods are
- Init
- Service
- destroy
Whenever something happens in the life of a servlet, the servlet engine calls these methods implicitly (automatically) and therefore known as life cycle methods. In javax.servlet.Servlet interface these three life cycle methods are declared (as abstract methods). Life cycle phases are as follows
- Instantiation phase (creating the object)
- Initialization phase
- Servicing phase
- Destruction phase
General Structure of a Simple User-Defined Servlet:
public class MyServlet implements Servlet { public void init (ServletConfig config) { // resource allocation code. For example, database connection and PreparedStatement creation code } public void service (ServletRequest request, ServletResponce responce) { // client request handling code (5 duties) } Public void destroy () { // resource de allocation code. For example, closing PreparedStatement and connection } //some other code may be here }
Instantiation phase of a Servlet:
The servlet engine creating the instance of the user-defined servlet is nothing but the instantiation phase of that servlet. Whenever the first client request comes for the servlet, the servlet engine creates the servlet instance.
In the lifetime of a servlet, it is instantiated only once. Only one servlet instance serves any number of client requests for that type of service i.e. a servlet is a single tone in java web application.
How is the Servlet Container loading and Instantiating the Servlet?
Dynamically the servlet container loads the servlet class and creates its instance.
Class c = Class.forName(“servlet class name dynamically received”);
Servlet s = (Servlet) c.newInstance();
Initialization Phase of a Servlet
The Servlet engine calling the init() method of the user-defined servlet is nothing but the initialization of the servlet. Initialization happens only once in the lifetime of a servlet.
During the initialization phase, the servlet instance is created but it doesn’t get complete servletness. Therefore, it can’t serve the client’s request. During the instantiation phase, a servlet is missing with two pieces of information.
- Context information
- Initial configuration information
The servlet engine encapsulates the above two pieces of information into the ServletConfig object and supplies its reference as an argument to the init method of the servlet. Once the init method is completely executed, the servlet is ready for serving the client request. For a better understanding of the different phases of a servlet, please have a look at the below diagram.
Servicing Phase of a Servlet:
Servlet Container calling the service method of the user-defined servlet is nothing but its servicing phase. Servlet Engine calls the service method for each client request i.e. servlet spends most of its life in the servicing phase only.
Servlet Container encapsulates user input into the ServletRequest object. Servlet Engine constructs the ServletResponce object also which is used by the servlet in building the response for the client. The Servlet Engine calls service methods by supplying the ServletRequest and ServletResponce object reference as arguments.
The service method is completely executed means one client request is served and the request-response cycle is completed. If concurrent multiple client requests come for the servlet, the container is multithreaded, for each client request, the container creates one thread and, in that thread, it creates a request and response object and invokes the service methods.
Destruction Phase of the Servlet:
Servlet Container calling the destroy() method of the user-defined servlet is nothing but the destruction phase of the servlet. Servlet Container calls the destroy() method only once in the lifetime of a servlet.
When the application is unloaded or the container is shut down by the administrator, the servlet Engine calls the destroy() method of the servlet and makes it for garbage collection.
Servlet Life Cycle Phase:
The life cycle of a servlet can be categorized into four phases:
- Loading and Instantiation
- Initialization
- Servicing the request
- Destroying the servlet
Loading and Instantiation
The servlet container loads the servlet during startup or when the primary request is formed. Loading of the servlet depends on the attribute of the web.xml file. If the attribute has a positive value then the servlet is loaded with the loading of the container otherwise it loads when the first request comes for service. The container creates the instances of the servlet after loading of the servlet.
Initialization
After creating the instances, the servlet container calls the init() method and passes the servlet container before the servlet can service any request. The initialization parameters persist until the servlet is destroyed. The init() method is named just one occasion throughout the life cycle of the servlet. The servlet is going to be available for service if it’s loaded successfully otherwise the servlet container unloads the servlet.
Servicing the Request
After successfully completing the initialization process, the servlet is going to be available for service. Servlet creates separate threads for each request. The servlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends a response to the client using the methods of the response object.
Destroying the Servlet
If the servlet is not any longer needed for servicing any request, the servlet container calls the destroy() method. Like the init() method this method is additionally called just one occasion throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container to not sent any request for service and therefore the servlet releases all the resources related to it. Java virtual Machine claims for the memory related to the resources for garbage pickup.
Servlet Life Cycle Methods:
The procedure followed by the technology to execute an application. The various stages that arise at the runtime when the application is under execution can be called as the life cycle. Servlets have three lifecycle methods and they are defined in Servlet Interface. The three lifecycle methods of servlet are:
- init()
- service()
- destroy()
init(): init() method would be executed by the container automatically as soon as an object of the servlet is created, the object of the servlet would be created only once. Thus init() method would be executed only once i.e. when the object of the servlet is created for the first time.
service(): service() method would be executed by the container automatically as and when the request is coming to as servlet. A container always calls the service() method by passing the data (i.e. coming from the client) in the form of ServletRequest object and address of the client (from where the request is received) in the form of servletResponse object as arguments.
destroy(): destroy() method would be executed before the object of the servlet is deleted. The container maintains every servlet object for a certain period of time even if no request is coming to that servlet. After a certain period of time container deletes the object of the servlet before deleting or destroying the servlet object. The container automatically calls the destroy() method and executes the destroy() method completely and after the execution of the destroy() method, the servlet object would be completely deleted.
Since init(), service() and destroy() methods are automatically executed by the container based on certain conditions representing different stages of a web application or servlet application we call them as LifeCycle methods of a Servlet.
In the next article, I am going to discuss Steps to Create Servlet Application in detail. Here, in this article, I try to explain the Life Cycle of Servlet in Java. I hope you enjoy this Life Cycle of Servlet in Java article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.