05 -Servlets Life Cycle

5.1 INTRODUCTION TO SERVLETS LIFE CYCLE

In this chapter we will discuss the life cycle of a servlet. Before moving to servlet life cycle let me recap the very important points we discussed in earlier chapters.

  1. “By default one and only one instance of a servlet gets created in a JVM”. I will keep on focusing on this point in this entire chapter so by the end of this chapter we all must understand this concept.
  1. “Life cycle of a servlet is managed by a Servlet Container and that is why servlets are also known as container managed objects”

These are very important concepts and most of us get confused with these concepts specifically on number of instances because Servlet is a web based model and servlet can be accessed my multiple concurrent users so how the request gets handled.

By this chapter we all know that for any class to become a servlet, it has to either extends GenericServlet class or HttpServlet Class

5.2 SERVLETS LIFE CYCLE

When a first request comes for a particular servlet, container does the following

  1. Loads the class of servlet
  2. Create an instance of servlet
  3. Initialize the servlet by calling init() method
  4. Once servlet is initialized,it is ready to serve the requests.
  5. For each request, container spawns a new thread and that thread executes service() method od a servlet.
  6. When container decides to destroy the servlet, it invokes destroy() method of the servlet.

Below figure is the picture of a servlet which faces all methods discussed above,

Step 1, 2 and 3 are executed only once, when the servlet is initially loaded.

Step 4 is executed multiple times - once for every HTTP request to the servlet.

Step 5 is executed when the servlet container unloads the servlet.

 

 

5.3 EACH SERVLET LIFE CYCLE PHASE IN DETAIL

1. Load Servlet Class

For any java class to come in to execution mode, it has to be loaded and servlets are not exception. Servlet class has to be loaded before a servlet can be invoked by the servlet container so the servlet container must first load its class definition. Process of loading servlet class is same as any other java class loading process.

Now it should be clear that this phase happens only once for a particular servlet and reason is simple “One and only one instance of a servlet is created”.

2. Create Servlet Instance

Once the servlet class is loaded, the servlet container creates an instance of the servlet. As we all know instance of each class has to be created before it actually works (ignoring static concept right now).

Container executes this phase only once for a particular servlet because “One and only one instance of a servlet is created”

3. Initialize servlet (Container Call the Servlets init() Method)

This phase is typically used to do initialization processing of a servlet. The init method is called only once when the servlet is first created, and not called again for each user request. When a servlet instance is created, its init() method is invoked. In this method we can get the initialization or init parameters configured for the servlet in web.xml file like below.

<servlet>

     <servlet-name>MyFirstServlet</servlet-name>

    <servlet-class>MyFirstServlet</servlet-class>

   <init-param>

        <param-name>param-name</param-name>

        <param-value>param-value</param-value>

   </init-param>

</servlet>

Typical use of init method is to do one time initializations like database initialization or load some one time data. Gist is – this method should be used for one time activity.

init() method definition looks like below

      public void init() throws ServletException

     {

     }

4. Call the Servlets service() Method

This is the main method that performs business logic and responsible for processing client request. When a new request for a servlet comes, servlet container spawns a new thread.

Then the thread executes the service() method and executes the business logic or the intended task of the servlet.

Service() method definition looks like below

      public void service(ServletRequest request, ServletResponse response)

     throwsServletException, IOException

     {    

     }

As you can see, service() method takes two arguments of type request and response. With the help of request argument, we can get the session, can get the user inputs. Similarly response helps to write back the response to the client,

Request can of several types like (GET, POST, PUT, DELETE, etc.) and The service() method checks the HTTP request type and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

So in nutshell-

for each request, service method gets executed which in-turn calls doGet(), doPost(),doPut(), doDelete() etc depending on the type of request

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.

We will discuss about doGet() and doPost() in detail in upcoming chapters but let’s have an overview about these methods

doGet()- Default request type for every request is “GET” which means if we do not specify any method, it will be considered as GET request. As it names implies ideally it should be used to GET something from server (though we can use GET to send data as well).

public void doGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

}

doPost()- This method is generally used to submit the data to server.To make any request of type POST, we need to specify attribute method as “POST”

     public void doPost(HttpServletRequestrequest,HttpServletResponse response)

    throwsServletException, IOException {

    } 

Thus, this step in the life cycle can be executed multiple times.

5. Call the Servlets destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet and thus gives an opportunity to the servlet to perform some cleanup activities like database connection close , closing of any files opened etc. We can relate it to finalize method that gets execute before GC of an object.

This step is only executed once, since a servlet is only unloaded once.

A servlet is unloaded by the container in possibly two scenarios –

  1. if the container shuts down,
  2. if the container reloads the web application at runtime.

After the destroy() method is called, the servlet object is marked for garbage collection.

The destroy method definition looks like this:

    public void destroy() {

   }

As mentioned above, servlet is loaded when first request for that servlet comes. There are scenarios where we need to get it loaded even before that or we can say at the time of application deployment. To do that, we can set the <load-on-startup> property of servlet configuration in web.xml

If we do not specify a <load-on-startup> element, the servlet container will typically load your servlet when the first request arrives for it.By setting a <load-on-startup> element, we tell the servlet container to load the servlet as soon as the servlet container starts.

    <servlet>

       <servlet-name>MyFirstServlet</servlet-name>

       <servlet-class>MyFirstServlet</servlet-class>

       <init-param>

            <param-name>param-name</param-name>

            <param-value>param-value</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

   </servlet>

The number inside the <load-on-startup>1</load-on-startup>  indicates the servlet container, the sequence in which the servlets should be loaded.  First the  lower numbers are loaded and in case the  value is unspecified or negative,  the servlet container can load the servlet at any time.

5.4 Quiz /Exercise

Let’s have a quick and small questions on what we have discussed in this chapter.

Scenario 1 - Assume there is a web application “Display Message” which has a one servlet “Display Message Servlet”. Display Message Servlet has a below print statements in each of life cycle methods

Method name

Print statement in corresponding message

Init()

Init method executed

Service

Service method executed

Destroy

Destroy method executed

Now there are two users who make the request to Display Message Servlet of DisplayMessage web application. What would be the output?

Answer – As we know only one instance of a servlet is created no matter how many request are coming so below will be the output. Service method will be executed as many times requests are coming.

Init method executed

Service method executed

Service method executed

You must be wondering why “Destroy method executed” is not printed. Reason is that destroy method will be executed only when servlet gets destroyed so you will see this message when you un-deploy your web application OR when you shut down the server.

Scenario2- I have a requirement where one of my servlet (Load Servlet) loads some data and rest all other servlets gets that data from Load Servlet. What is the important thing we need to consider?

Answer- Since all other servlets are dependent on Load Servlet, which means we need to get the Load Servlet loaded first. To do this we need to add <load-on-startup>1</load-on-startup>

Like us on Facebook