Servlet Life Cycle

Servlet Life Cycle

 

The Servlet’s life cycle is controlled by the servlet container or web container in which servlet has been deployed, resides in the Web server (most commonly used Web server is Apache tomcat).

Whenever request comes from browser, the container performs the following steps

Init() method

First it checks for the existence of servlet’s instance, if an instance of servlet is not created

  • It loads the servlet class (Class loader will take care of loading the appropriate servlet class)
  • Servlet class instance is created (Container will create an instance of servlet once servlet class loaded. Servlet instance will be created only once in the life cycle)
  • Instance created so next step is need to initialize the servlet instance by calling the famous init method 🙂 🙂 . This method is available in javax.servlet.Servlet interface

public void init(ServletConfig config) throws ServletException.

config – a ServletConfig object which contains the servlet’s configuration and initialization parameters.

All operations such as one time initializations and getting DB connection, parsing the settings.xml, reading properties etc. will be done inside this method in other words this method creates or loads the data that will be used throughout the servlet life cycle

 

service() method

If an instance is already created, then it will invokes the service method by passing request and response objects.The web container calls this service method each and every time when request for the servlet is received. Entire business logic will be done in this method

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

service method is called by container and based on the request type service method invokes doGet, doPost, doDelete, doPut, doTrace, doOptions, doHead appropriately. So as a developer we need to override appropriate method based on the business need.

Java Servlets

Java Servlets life cycle

destroy()

The destroy() method is called only once at the end of servlet life cycle. It is called once all the threads in the particular service method is exited or it reaches certain time period (which user configures).

In this method we can write all cleanup activities such as closing DB connection, cleanup any resources such as memory, file handlers, threads etc. After the destroy method is called servlet object is eligible for Garbage collection.

Just simply calling destroy method wont unload the servlet’s instance as we cannot manage the servlet’s life cycle, it will be taken care by container itself.

Once destroy method is called it won’t call the service method again for that particular servlet.

Leave a Reply

Your email address will not be published. Required fields are marked *