Friday 30 August 2013

Servlet Life Cycle in Details

Servlet Life Cycle can be defined as the complete process from the servlet creation to the destroy of Servlet.

The Servlet life cycle goes through following steps,
1-Loading
2-Initialization
3-Service(Request Handling)
4-Destroying


Now we will look in to all the steps in details one by one,

Servlet Life Cycle Diagram
Pic-Servlet Life Lycle

1-Loading-
In this steps container or server will load the Servlet for further use.This step can be categories in two steps for better understanding.Lets look in to the Loading process,

a)Loading- Container will loads a servlet class by using normal java class loading option.

b)Initialization:

i)If servlet is not hosted in the distributed environment and it does not implements SingleThreadModel interface, the container will create only one instance.

ii)If servlet is hosted in the distributed environment the container will create one Servlet instance per JVM.

iii)If Servlet implements SingleThreadModel interface, the container may create multiple instance for Servlet, if in this case the servlet is hosted as distributed, the Servlet container may create multiple instance per JVM.

2-Initialization-
After the Servlet is instantiated successfully, the servlet container initializes the instantiated Servlet object. The container initialize object by invoking init(ServletConfig) method. Container creates one ServletConfig object per Servlet.Servlet container invokes init(ServletConfig) method once immediately after the Servlet object is instantiated successfully.

3-Service-
After initialization the servlet instance is ready to serve client request. The container performs the following operation when instance is located to service a request,

i)Container creates ServletRequest and ServletResponse object.

ii)After creating request, response object container invokes service(ServletRequest, ServletResponse) method. Following are cases occur while dealing with multiple request,

a)If Servlet does not implements SingleThreadModel interface container uses single instance of servlet to process multiple request at a time.
b)If Servlet does implements SingleThreadModel interface container uses single instance of servlet to process only one request at a time. If Servlet is marked as distributed then separate pool of Servlet instances in each JVM.

4-Destroying-
Container calls destroy() method where it release all resources which has allocated.The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

No comments:

Post a Comment

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...