So, lets get started!!!
The Servlet Lifecycle
The servlets life cycle begins when it gets initialized and the servlet is alive as long as it needs to be while it services requests and then it gets killed when it is no longer required. The usual order in which the three important methods of the servlet get called are:
2. service() and then
One of the most common questions that can test your knowledge about Servlets is about when the init() method gets called. Knowledge of the servlets lifecycle is crucial to answering these kind of questions. You need to remember that the init() method may be called when the server starts, when it is first requested and sometimes the container management console will allow you to call it as part of server administration. The exam expects you to know that the init() method will only be called once per servlet instance. It is not used to receive or send information back to the server but, it throws a ServletException to the container that calls the servlet in case anything goes wrong.
The init method is called first, the first time the servlet is invoked. This happens one time and I mean only one time. However, the service method is called every time a servlet is requested by some user action on a web page. Finally, the destroy method is called one time and I mean again one time, upon the removal of the servlet from memory due either to explicit removal or lack of use (for example, the session expires).
You can configure the container to load certain servlets upon startup (
The destroy() method, like init(), is called only once. It is called when the servlet is taken out of service and all pending requests to a given servlet are completed or have timed-out. This method is called by the container to give you a chance to release resources such as database connections and threads. You can always call super.destroy() (GenericServlet.destroy()) to add a note to the log about what is going on. You might want to do this even if only to place a timestamp in there.
DESTROY() is not called if the container crashes! You should log activity from somewhere other than the destroy() method if a given piece of information is essential, but might not be logged if the logging functionality is placed in the destroy() method. This is because the destroy() method is not called if the Servlet Container quits abruptly (crashes).
In the below image you can see that, the service methods are the only onces that get called everytime the user performs an action through the web browser. The init and destroy methods get invoked once when the servlet is initialized or destroyed.
Previous Chapter: Chapter 16 - Servlet Context
Next Chapter: Chapter 18 - Using Request Dispatcher