Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA SERVLET

Life Cycle of A Servlets

Servlet Life Cycle

A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated and initialized, handles requests from clients, and how it is taken out of service. This life cycle is expressed in the API by the init, service, and destroy methods of the javax.servlet.Servlet interface that all servlets must, directly or indirectly through the GenericServlet or HttpServlet abstract classes, implement.


1.     Loading and Instantiation

The servlet container is responsible for loading and instantiating a servlet. The instantiation and loading can occur when the engine is started or it can be delayed until the container determines that it needs the servlet to service a request. First, a class of the servlet’s type must be located by the servlet container. If needed, the
servlet container loads a servlet using normal Java class loading facilities from a local file system, a remote file system, or other network services. After the container has loaded the Servlet class, it instantiates an object instance of that class for use. It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.

2.    Initialization

After the servlet object is loaded and instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read any persistent configuration data, initialize costly resources (such as JDBC™ basedconnection), and perform any other one-time activities. The container initializes the servlet by calling the init method of the Servlet interface with a unique (per servlet definition) object implementing the ServletConfig interface. This configuration object allows the servlet to access name-value initialization parameters from the servlet container’s configuration information. The configuration object also gives the servlet access to an object implementing the ServletContext interface which describes the runtime environment that the servlet is running within.

3.    Destruction of Serlvet

Servlets run until the server destroys them, for example, at the request of a system administrator. When a server destroys a servlet, the server runs the servlet's destroy method. The method is run once; the server will not run the destroy method again until after the server reloads and reinitializes the servlet.

The Servlet Life Cycle

 


Previous

Next