Servlet life Cycle--A simple overview

January 13, 2012

Mostly a Servlet is having 3 major stages.

  1. Initialization----init() method
  2. Service--------service()method
  3. Destruction----Destroy() method

Init method:

Init() is the method when a servlet starts and a servlet's life cycle begins. It is called when server instantiated the servlet. The major advantage is ,it is called only once in its life cycle. Init method create or initializes all the required resources that will will be used during it's life time.

The Signature is --
public void init(ServletConfig config) throws ServletException 
it takes the ServletConfig object as a parameter and pass it to the super init method.

So the structure of a init method looks like---
            public void init(ServletConfig config) throws ServletException {

The important aspect of this signature is that a init method can throw an exception ServletException.When it occures??? If the init method could not initializes all the required resources that will will be used during it's life time.

Service method:

As picture depicts, once the init method is called , the second step is to call Service method. So Service method can not be called if the init method is not called. This methods actually talk to client ..i mean this method takes care of the request and response. We generally do not implement this method but if our servlet class is extended  to GenericServlet then we need to implement that.Service method support HTTP /1.1 and above.
The method looks like-

            protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

Destroy method:

This method is the end of servlet's life cycle.if we shut down a service , this method is automatically called. All the resources that were consumed by init method is released. This is kind of garbage collection of core java. Also some important aspect like closing database connection,closing file system or any important information if required for next run.
The method looks like--
 public void destroy() 

You Might Also Like