Java Servlet Life Cycle
Today I am discussing about Java servlet life cycle . Servlets
run on server as a same part or process of web server but all the task
(Initializing ,invoking ,destroying) performed by web server.
The main three methods to communicate with servlet are:
1.init()
2.service()
3.destroy()
Ancillary methods are:
1.getServletConfig ()
2.getServletinfo()
Details of the mentioned methods:
1.init () Method: Init() method is invoked at the start when
a servlet is loaded for first time .Init() method works like a introductory ,Init()
method perform setup processes like establishing connections with web servers .Init
() has one argument, a reference to a ServletConfig object which provides initialization arguments for the servlet.
2.Service () Method :The main functional method in servlet
life cycle is Service() method .When client sent request to server the
Service() method listen it and give response for each request .Service method
takes two parameters:
ServletRequest and ServletResponse.A ServletRequest object
gets data from the client.ServletResponse gives response of ServletRequest.
When preparing a response, the method setCotenType () is called first to set
the MIME type of the reply. Next, the method getoutputStream () or getWriter ()
can be used to obtain a ServletOutputStream or PrintWriter, respcitively, to
send data back to the client.
3.Destory () Method :Main function of Destroy () method is
to clean up any resources (like open files or db connections) before the
servlet is unloaded .If there is no clean-up operations, Destroy() method can
be an empty method .Destroy() method is invoked when all the service request is
completed or task timing is over .So if service method is running Destroy()
method can not perform its operation.
Java Servlet Life Cycle
Reviewed by Abdul Moid
on
November 18, 2015
Rating:
