Before we go on, a few words about the lifecycle of servlets is in order. There are three methods implement the lifecycle of a servlet: init()
, service()
, and destroy()
. Prior to handling client requests, the servlet is instantiated and initialized by the servlet container (Tomcat in our case). Only one instance of each servlet is instantiated by the servlet container. During this initialization phase, the container calls init()
to give the servlet a chance to run initialization code. Servlets operate in a multithreaded fashion, which means that their methods may be invoked by a number of threads. Upon receiving the first client request, the container starts a new thread or allocates one from the pool. Then, the execution of the servlet is assigned to that thread, which carries on by invoking the servlet's service()
method.
Tip
It is worth emphasizing that init()
is executed only once. Also the container is not able to invoke service()
before init()
completes.
service...