Ilias Koutsakis

About Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.

Servlet Lifecycle Example

In this example we are going to examine what is the servlet lifecycle and how it all works out in the servlet container. Basically, by “lifecycle”, we actually mean the whole process of creating and initializing the servlet, using it and destroying it when it is no longer needed. In the GenericServlet abstract class (which is extended by all the other servlet implementations, like the popular HttpServlet), there are three basic methods that achieve the above. Let’s take a look at them.

 

 

 

1. Servlet Lifecycle methods

The mehods that represent the lifecycle of a servlet are these three:

  • init(): This method is automatically called whenever a servlet is initialized. The developer does not explicitly call the init() method, instead, it is automatically called the first time the servlet is called through a URL request. Only one instance of each servlet is created and used, and each folowing request creates a new thread that handles it.
  • service(): This is the main method of handling the requests to the server. This method determines the type of the request (POST, GET, etc) and acts accordingly, by calling the specified methods like doPost() and doGet().
  • destroy(): The destroy method is working similarly to init(), but trying to achieve the opposite result. It is not a method that is explicitly called by the developer. Instead, when the server (servlet container) decides that the servlet is no longer in use, and its resources should be collected and used somewhere else, the destroy() method is automatically called. In that case we use destroy() to close connections, free resources and generally finalize whatever needs to be finalized for a smooth shutdown of the servlet and no memory leaks. After the servlet is destroyed, the garbage collector collects all the previously held resources.

A quick diagram describing the whole process could be this:

The three states of a servlet lifecycle, as descibed by their methods.

The three states of a servlet lifecycle, as described by their methods.

2. Servlet Lifecycle Example

Let’s create a simple Dynamic Web Project in Eclipse, where we will see in action how the servlet lifecycle works.

index.jsp

<%@ page language="java" 
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Servlet Lifecycle Example</title>
</head>
<body>
  <form action="ServletLifecycle" method="post">
      <input type="submit" value="Make request" />
  </form>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    
    <servlet>
      <servlet-name>ServletLifecycle</servlet-name>
      <servlet-class>ServletLifecycleExample</servlet-class>
    </servlet>

    <servlet-mapping>
      <servlet-name>ServletLifecycle</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

ServletLifecycleExample.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletLifecycleExample extends GenericServlet {
    
    @Override
    public void init() {
        // initialize the servlet, and print something in the console.
        System.out.println("Servlet Initialized!");
    }

    @Override
    public void service(ServletRequest request, ServletResponse response)
            throws ServletException, IOException {
        
        // the service method will 
        response.setContentType("text/html");
        
        PrintWriter out = response.getWriter();
        out.println("Servlet called from jsp page!");
    }
    
    @Override
    public void destroy() {
        // close connections etc.
    }
}

Output

Lets take a look at the output of the above application. What we should see is a simple web page, and as soon as we push the button to make the request, only then the servlet will be initialized.

Before the request…

The jsp page that will make the request.

The jsp page that will make the request.

And after the request.

The result of the request. Check out the logging console, where among the server messages we also have the message from the init method!

The result of the request. Check out the logging console, where among the server messages we also have the message from the init method!

3. Download the example

This was an example of the servlet lifecycle.

Download
You can download the full source code of this example here : ServletLifecycleExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close