Learn Servlet Life Cycle
If we talk about Servlet Life Cycle, we would need to cover the entire process starting from its initialization till the destruction which is basically wrapped in four stages that are:
This is the initial stage of Servlet Life Cycle in which servlet container loads the servlet from web.xml, which is done either during initiation or when the first request is made. If the attribute <load-on-startup> of web.xml file has a positive value then the Servlet will be loaded else it will load when the first request comes for service. After loading of the servlet, the container creates the instances of the Servlet by using Class.forName(ServletName).newInstance().
Once the instances are created the second stage called Initialization begins in which the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. One thing that is to be known is, the init() must be called by the servlet container prior to the Servlet can serve any request. The initialization parameter continues until the Servlet is destroyed. The init() method is called only once during the entire life cycle of the servlet. The servlet will only be available for service if it is servlet code is loaded successfully without any error otherwise it will be not available for service.
Once the initialization process has been completed successfully, the Servlet becomes available for service. Moreover, servlet creates a separate thread for each of the request made and the the servlet container calls the service() method for servicing any request. The service() method evaluates the kind of request and calls the suitable method (doGet() or doPost()) to execute the request and send response to the client using the methods of the response object.
If the Servlet is no longer needed to serve any request further, the servlet container calls for the destroy() method. Like the init() method this destroy() method is also called only once in the entire life cycle of the servlet. Once the destroy() method is called, it indicates to the servlet container not to send any request for service and the Servlet releases all the resources related to it. Java Virtual Machine is responsible for the memory associated with the resources for garbage collection.
For complete Servlet Life Cycle Example: Click here
Recommend the tutorial