Before start writing the servlet, it is important to know the life cylce of every servlet instance created. Read What is Servlet? tips to know about the servlet basics.
also read:
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 theservice() 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.
Single Thread Model
Although it is standard to have one servlet instance per registered servlet name, it is possible for a servlet to elect instead to have a pool of instances created for each of its names, all sharing the duty of handling requests. Such servlets indicate this desire by implementing the javax.servlet.SingleThreadModel interface. This is an empty, tag interface that defines no methods or variables and serves only to flag the servlet as wanting the alternate life cycle. A server that loads a SingleThreadModel servlet must guarantee, according to the Servlet API documentation, “that no two threads will execute concurrently the service method of that servlet.