login

Java Servlet Lifecycle

In this tutorial, you will have a basic understanding of servlet lifecycle including loading, initialization, execution and clean up.

Basically a Servlet goes through four phases as follows:

  1. Loading
  2. Initialization
  3. Execution
  4. CleanUp

Let's examine each phase in the servlet lifecycle in a greater details.

Servlet Loading

There are three scenarios when a servlet can be loaded:

  • When the web server starts up
  • When the Sytem Administrator configure the server to load the servlet
  • When client request to run a servlet

In order to load a servlet, the server needs to know what servlet to load. Servlet is determined by its name. The name of servlet is including package and class name. For example, you have package jsptutorial  and servlet HelloWorldServlet hence the servlet name is jsptutorial.HelloWorldServlet.

When the browser asks for a servlet for example: http://localhost:8080/servlet/jsptutroial.HelloWorldServlet , the servlet engines checks for the servlet name HelloWorldServlet and load it by using class loading feature of Java. You can also map a specific URL to a specific servlet.

Servlet Initialization

After the servlet is loaded into memory, the servlet engines initalize it by calling the following method:

public void init(ServletConfig config)
    throws ServletException

In the method init, the config object is an instance of ServletConfig class. The config object contains initialization parameters and a ServletContext instance. The initialization parameters are specific to each servlet and configured within the servlet engine in the deployment descriptor as part of the definition of the servlet itself. To change or add new initialization parameter to the servlet you need to edit the deployment descriptor file which is an XML file like following:

<servlet>
...
<init-param>
    <param-name>id</param-name>
    <param-value>10</param-value>
</init-param>
<init-param>
    <param-name>page</param-name>
    <param-value>2</param-value>
</init-param>
...
</servlet>

Servlet Execution

After a servlet is initalized, it is executed by calling servlet's method called service and passing the ServletRequest and ServletResponse objects as parameters. At this time the servlet handle request and response to the request and return its to the browser.

Servlet Cleanup

Servlet is only unloaded by garbage collector or system restart or shutdown. At this phase, the servlet engines call the method destroy of the servlet. In this method you can deallocate the resources you've used in the servlet which cost intensive memory and you decide to release it without waiting for garbage collector of Java engine.