Friday, February 12, 2010

Servlet Life Cycle

Servlet Life Cycle Methods

The following are the life cycle methods of a servlet instance:
  • init()
  • service()
  • destroy()
We will look into the each method in detail.

init()

This method is called once for a servlet instance. When first time servlet is called, servlet container creates instance of that servlet and loaded into the memory. Future requests will be served by the same instance without creating the new instance. Servlet by default multithreaded application.init() method is used for inilializing servlet variables which are required to be passed from the deployment descriptor web.xml. ServletConfig is passed as the parameter to init() method which stores all the values configured in the web.xml. It is more convenient way to initialize the servlet.

service()

This method is called for the each request. This is the entry point for the every servlet request and here we have to write our businesslogic or any other processes. This method takes HttpServletRequest and HttpServletresponse as the parameters. It is not mandatory to write this method, normally developers are interested in writing doGet() or doPost() methods which is by default called from the service() method. If you override service(), it is your reponsibility to call the appropriate methods. If you are not overridden the service() method, based on the types of the request the methods will be called.

destroy()

This method will be called once for a instance. It is used for releasing any resources used by the servlet instance. Most of the times it could be database connections, Fill IO operations, etc. destroy() is called by the container when it is removing the instance from the servlet container. Servlet instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.


No comments:

Post a Comment