16 The Servlet Life Cycle
Pravin Jain
What is a servlet?
Servlet is a server side component which receives a request from a client, processes the request and sends a content based response back to the client. The Servlet is a separate API, it is not part of the standard Java API. The Servlet as it runs on the server side, is embedded inside a Server. Most commonly the servlets are used for HTTP protocol, and are embedded inside a WebContainer. Common implementations of the Servlet specifications are Glassfish, Tomcat, jRun, jBoss, Jetty, etc.. Tomcat used to be the reference implementation for the servlet specifications, since Servlet specifications 3.0, Glassfish is the reference implementation. The Servlet specifications are managed independent of the standard Java specifications. There was a major standardization in the Servlet specifications version 2.0. It standardized the directory structure for deployment of the Servlet and related components, and introduced the concept of a web application. current specification is version 3.0.
The Servlet specification is designed in generic way for any server which uses request response based protocol. There are 2 packages in the servlet API
- javax.servlet, which is generic, and
- javax.servlet.http, which is an extension of the generic APIs in the javax.servlet, and specific to HTTP protocol.
Servlet specifications mandate the implementations to support HTTP protocol. An implementation can also support other protocols, e.g., there are implementations which also support the SIP protocol.
So in general a servlet is a component which is embedded inside some ServletContainer This is something similar to an Applet being embedded inside a Browser. which is a container for the Applet.
Number of servlets can be configured in a single web application. In turn several web applications may be deployed on a single instance of a WebContainer.
Architecture Diagram:
The life-cycle of a Servlet is controlled by the container in which the Servlet has been configured as part of a deployed web application.
The configuration of a web application maps URL patterns to Servlets.
When a ServletContainer starts, it would first look for all the deployed web applications. Then it would create an instance of ServletContext corresponding to each web application, similar to an AppletContext being created for each html page containing any applet tag inside a browser.
It would then find out the Servlets which are configured in web application. A Servlet may be configured to be loaded at the startup of web application. For each servlet configured to be loaded on startup, it would create an instance of ServletConfig, similar to an AppletStub being created for each Applet in the html page inside a browser. These Servlet instances are then initialized by invoking init() method and passing corresponding ServletConfig instance.
When a request arrives from a client, based on the URL, Servlet would be identified and the following steps would be performed on the identified Servlet :
- If an instance of the Servlet does not exist, the web container (this may happen for Servlets which are not configure to load at startup) :
- Loads the Servlet class.
- Creates an instance of the Servlet class.
- Creates an instance of ServletConfig based on configuration information related to this Servlet.
- Initializes the Servlet instance by calling the init() method. The aforesaid ServletConfig instance is passed to init() method.
- Invokes the service method, passing request and response objects.
- If it needs to take the servlet out of service, the container finalizes the servlet by calling the Servlet’s destroy() method.
Creating and Initializing a Servlet
The web container initializes a servlet after loading and instantiating the servlet class and before delivering requests from clients. To customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities. If it cannot complete its initialization process, a servlet throws an UnavailableException.
A Servlet can be configured with initialization parameters which are made available to the Servlet through ServletConfig object. Initialization parameter can be used to provide data needed by a particular servlet..
Web container would create instance of the deployed Servlet using its default constructor. Next it would invoke the first method on the instance of Servlet. This method is the init() method. similar to the
void setStub(AppletStub stub)
of the Applet.
Here the init() method also has a parameter which is the ServletConfig.
void init(ServletConfig cfg) throws ServletException
So the first life cycle method of a Servlet is init. Servlet
In case the init() method invocation on a Servlet fails by throwing a ServletException, the web container would take the Servlet out of service. The init() method may also fail by throwing UnavailableException ( sub-class of ServletException). The UnavailableException may indicate a duration for unavailability. In such case, the web container may recreate Servlet and try initialization again after the specified duration.
Request Processing
The request processing for a servlet is handled by its service method. The term service method is used for any method in a servlet class that provides a service to a client.
After startup of web container is completed, it becomes ready to accept requests from client and give response back to the client. When a request arrives from the client, the web container first identifies the servlet for which this request has arrived based on URL. It would then encapsulate information available in the client request in an instance of ServletRequest. It would also allocate a Buffer and encapsulate it in an instance of ServletResponse. This Buffer is to be used by the Servlet to write the content which it wants to send back to the client. After creating the instance of ServletRequest and ServletResponse, it now invokes the service method on the instance of Servlet.
void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
So the implementation of the service method by the Servlet is supposed to look at the information in the ServletRequest object, do some processing and then setup a response content in the buffer of the ServletResponse object. Once the service method is over, web container sends the content available in the buffer according to the protocol.
In case the service() method invocation on a Servlet fails by throwing a ServletException, the web container would first invoke destroy() on the Servlet and then takes it out of service. The service() method may also fail by throwing UnavailableException ( sub-class of ServletException). Here also the web container would first invoke destroy() on the Servlet and then takes it out of service. The UnavailableException may indicate a duration for unavailability. In such case, the web container may recreate Servlet and try initialization again after the specified duration to bring it back to ready for request processing.
If any request is received by web container for the Servlet which is out of service, web container directly gives appropriate negative response to the client without trying to invoke the service() method.
Finalizing a Servlet
All web containers (Servlet containers) provide administrative tools to manage the deployment and other activities related to web application such as start, stop, undeploy etc. When an application is stopped or restarted, then the Servlet Container would destroy all the Servlet instances created for that application. The Servlet Container invokes the destroy() method before it destroys the Servlet instance.
Whenever the web container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources or when it is being shut down). In such a case, the container calls the destroy() method of the Servlet interface. In this method, you release any resources the servlet is using and save any persistent state. The destroy method releases any resources which it has acquired during initialization using the init method.
The web container normally tries to ensure that there is no client request processing in progress before before calling the destroy method.The server tries to ensure this by calling the destroy method only after all service requests have returned or after a server-specific grace period, whichever comes first. If your servlet has operations that may run longer than the server’s grace period, the operations could still be running when destroy() is called.
Summary :
So in the life cycle of an Servlet. init is the first method which will be invoked when the application starts, this will be followed by service method being invoked whenever a client requests, and then when the application stops the destroy method is invoked.
you can view video on The Servlet Life Cycle |
- Core Servlets and Java Server Pages Volume 1 by Marty Hall & Larry Brown, Second Edition, Pearson Education.
- Inside Servlets by Dustin R Callaway, Pearson Education.
- Java Server Programming for Professionals by Ivan Bayross, Sharanam Shah, Cynhthia Bayross and Vaishali Shah Shroff Publishers and Distributros.
- http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-oth-JSpec/