2.5 Servlet Lifecycle


The servlet lifecycle is simple; there's only one main state-initialized.
If the servlet isn't initialized, then it's either being initialized (running its constructor or init()method), being
destroyed (running its destroy() method), or it simply does not exist (Bates, Sierra and Basham 2008).
Figure 2.21: the servlet Life cycle

The servlet starts life when the Container finds the servlet class file. This virtually always happens when the
Container starts up (for example, when you run Tomcat).
When the Container starts, it looks for deployed web apps and then starts searching for servlet class files.

2.5 Servlet Lifecycle


After the servlet instance is created, the Container calls init() on the servlet instance before the servlet can
service any client requests.
When the first client request comes in, the Container starts a new thread or allocates a thread from the pool, and
causes the servlet's service() method to be invoked.
This service() method looks at the request, determines the HTTP method (GET, POST, etc.) and invokes the
matching doGet(), doPost(), etc. on the servlet (Bates, Sierra and Basham 2008).
When the servlet is first created, its init method is invoked, so init is where you put one-time setup code (like
getting a database connection or registering yourself with other objects).
After this, each user request results in a thread that calls the service method of the previously created instance.
Multiple concurrent requests normally result in multiple threads calling service simultaneously, although your
servlet can implement a special interface (SingleThreadModel) that stipulates that only a single thread is
permitted to run at any one time.
The service method then calls doGet, doPost, or another doXxx method, depending on the type of HTTP
request it received.

2.5 Servlet Lifecycle


Finally, if the server decides to unload a servlet, it first calls the servlet's destroy method (Hall and Brown
2004).

Figure 2.22: the container runs multiple threads to process multiple requests to a single servlet


2.5 Servlet Lifecycle


Servlet initialization
A servlet moves from does not exist to initialized (which really means ready to service client requests), beginning
with a constructor.
But the constructor makes only an object, not a servlet.
To be a servlet, the object needs to be granted servletness.
You might have servlet initialization code, like getting web app configuration info, or looking up a reference to
another part of the application, that will fail if you run it too early in the servlet's life.
It's pretty simple though, if you remember to put nothing in the servlet's constructor! There's nothing that
can't wait until init() (Bates, Sierra and Basham 2008).
In lifecycle, when an object is goes from being a regular object to being a servlet, two objects are created a
ServletConfig object and a ServletContext object.
For now just highlight the following points (Bates, Sierra and Basham 2008):
A ServletConfig
One ServletConfig object per servlet.

2.5 Servlet Lifecycle


Use it to pass deploy-time information to the servlet (a database or enterprise bean lookup name, for
example) that you don't want to hard-code into the servlet (servlet init parameters).
Use it to access the ServletContext.
Parameters are configured in the Deployment Descriptor.
A ServletContext
One ServletContext per web app. (They should have named it AppContext.)
Use it to access web app parameters (also configured in the Deployment Descriptor).
Use it as a kind of application bulletin-board, where you can put up messages (called attributes) that
other parts of the application can access (way more on this in the next chapter).
Use it to get server info, including the name and version of the Container, and the version of the API
that's supported.
The init method is designed to be called only once.
It is called when the servlet is first created, and not called again for each user request.
So, it is used for one-time initializations, just as with the init method of applets.

2.5 Servlet Lifecycle


The init() method simply creates or loads some data that will be used throughout the life of the servlet(Hall and
Brown 2004).
The init method definition looks like this:
GenericServlet provides two overloaded forms of the method:
public void init() throws ServletException
public void init(ServletConfig) throws ServletException
As we mentioned in section 2.3.4, the deployment descriptor can define parameters that apply to the Servlet
through the <init-param> element.
The Servlet container reads these parameters from the web.xml file and stores them as name/value pairs in a
ServletConfig object.
Because the Servlet interface defines only init(ServletConfig), this is the method the container must call.
GenericServlet implements this method to store the ServletConfig reference, and then call the parameterless
init() method that it defines (Mukhar, et al. 2006).

2.5 Servlet Lifecycle


Therefore, to perform initialization, your Servlet needs to implement only the parameterless init() method.
If you implement init(), your init() will be called by GenericServlet; and because the ServletConfig reference is
already stored, your init() method will have access to all the initialization parameters stored in it (Mukhar, et al.
2006).

Request Handling
As each request comes to the Servlet container, the container calls the service() method of the appropriate
Servlet to handle the request.
Since you will almost always be subclassing HttpServlet, however, your Servlet only needs to override doPost()
and/or doGet() to handle requests (Mukhar, et al. 2006). Here are the signatures of those two methods:
As with init(), the Servlet can throw a ServletException or UnavailableException during the processing of a
request.

2.5 Servlet Lifecycle


If your Servlet throws either exception, then the Servlet container is required to stop sending requests to the
Servlet.
For a ServletException or for an UnavailableException that indicates a permanent unavailability (it was created
with no value for seconds unavailable), the Servlet container must end the Servlet's lifecycle (Mukhar, et al.
2006).

End of Life
When the Servlet container needs to unload the Servlet, either because it is being shut down or for some other
reason such as a ServletException, the Servlet container will call the destroy() method.
However, prior to calling destroy(), the container must allow time for any request threads that are still processing
to complete their processing.
After these threads are finished processing, or after a server-defined timeout period, the container is allowed to
call destroy() (Mukhar, et al. 2006).
Note that destroy() does not actually destroy the Servlet or cause it to be garbage-collected.
It simply provides an opportunity for the Servlet to clean up any resources it used or opened.

2.5 Servlet Lifecycle


Obviously, after this method is called, the container will not send any more requests to the Servlet (Mukhar, et
al. 2006). The signature of the destroy() method is as follows:
public void destroy()
The destroy() method allows the Servlet to release or clean up any resources that it uses.
For example, it can close database connections or files, flush any streams, or close any sockets (Mukhar, et al.
2006).
This method is implemented by the GenericServlet parent class, so if your Servlet does not need to perform any
cleanup, your Servlet does not need to implement this method.
After the destroy() method completes, the container will release its references to the
Servlet instance, and the Servlet instance will be eligible for garbage collection.
Although this method is public, it is meant to be called only by the Servlet container.
You should never call the destroy() method from within your Servlet, and you should not allow other code to call
this method (Mukhar, et al. 2006).