Servlet program executes under the supervision of container. All the life cycle methods are invoked by the web container according to the state change of servlet.
Servlet life cycle:
1 instantiation
2 initialization
3 service
4 destroy
5 unavailable
Brief description of life cycle:
Instantiation:
Web container creates the instance of servlet if not created, web application redeployed, or servlet engine restarted. Instance only created once by server.
Initialization:
Server initializes the instance of servlet after created and invokes init() method of servlet. Server initialize servlet instance only once.
Service:
Instance of servlet provides the service to incoming requests to server. server invokes service() method each time upon requests come from client to process and to generate response.
Destroy:
When servlet’s instance going to remove from memory, Server free all resources associated to servlet and invokes the method callback destroy().
Unavailable:
After invoking destroy() method, the servlet instance is deleted and set unavailable automatically by server.
Life cycle methods :
init()
it is life cycle’s method of servlet and this is invoked when server initialize the servlet instance. This method is used to provide initial parameters to servlet and it takes ServletConfig object as argument. It is called only once and after just servlet instance creation.
service()
this method is invoked by server for each request come from client. Here developer writes logics to process client’s request.
destroy()
this method is invoked by server when servlet instance about to destroy or going to unavailable. Developer use this method to process some finalization task like database connection closing, data flushing etc.
Comments