Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Servlet Life-cycle

1.5 Given a life-cycle method, init, service, or destroy, identify correct statements about its purpose or about how and when it is invoked.

The servlet life-cycle is not obvious. The container calls three methods—namely, init(), service() and destroy()—in that order. Ordinarily, that is how the container talks to your servlet. With some containers, you can modify this behavior, but the exam will assume this order.

When is init() called?

A common question on the exam tests your understanding of when init() is called. Knowledge of a servlet's life-cycle is crucial to answering these types of questions. Remember, init() may be called when the server starts (tell web.xml to load servlet upon startup), when first requested, and sometimes the container management console will allow you to call it as part of the server administration. The exam expects you to know that init() will only be called once per servlet instance, that it is not used to send information back to the browser (HttpServletResponse is not a parameter), and that it throws a ServletException to the container that called the servlet if anything goes wrong.

The init method is called first, the first time the servlet is invoked. This happens one time. However, the service method is called every time a servlet is requested. Lastly, the destroy method is called one time, upon the removal of the servlet from memory due either to explicit removal or lack of use (for example, the session expires). You can configure the container to load certain servlets upon startup (<load-on-startup/> in web.xml), but most of them will be loaded upon first request. Either way, the init method is called first. Place in this method things you will use across requests, like database connections, and class member values such as finalized constants.

The destroy() method, like init(), is called only once. It is called when the servlet is taken out of service and all pending requests to a given servlet (that one with the mentioned destroy() method) are completed or have timed-out. This method is called by the container to give you a chance to release resources such as database connections and threads. You can always call super.destroy() (GenericServlet.destroy()) to add a note to the log about what is going on. You might want to do this even if only to place a timestamp in there.

destroy() is not called if the container crashes!

You should log activity from somewhere other than the destroy() method if a given piece of information is essential, but might not be logged if the logging functionality is placed in the destroy() method. This is because the destroy() method is not called if the Servlet Container quits abruptly (crashes).

Listings 4.15 and 4.16 are sample Web applications (HTML page and servlet combination) that demonstrate how to use the init(), service(), and destroy() methods, and when they are called. You could combine them and just have one servlet, but there are two pieces here to illustrate the relationship between static and dynamic parts of an application. The first part, Listing 4.15, is the HTML page.

Listing 4.15 HTML Page That Works with Servlet in Listing 4.16 Illustrating the Relationship

<title>LifeCycle Demonstration Using SQL Server</title>
<body bgcolor="#FFFFFF"> 

<p align=center>
<h1>LifeCycle Demonstration Using DB</h1>
<form name="formSearch" method="post" action=
<table border="0" cellspacing="0" cellpadding="6">
   <td><b>Last Name</b></td> 
   <td><input type="text" name="LastName" 
   <td align="center"><input type="submit" name="Submit"

Servlet Reloading!

Servlets are loaded in one of three ways. The first way is when the Web server starts. You can set this in the configuration file. Reload can happen automatically after the container detects that its class file (under servlet dir, for example, WEB-INF/classes) has changes. The third way, with some containers, is through an administrator interface.

The HTML page contains a form with one field for a last name. When submitted, the container takes the lastname field and hands it to the servlet in the request object. This object is where you normally extract requester information. The servlet grabs the lastname, if any, and builds a SQL WHERE clause with it. Then the servlet establishes a connection with the database server (I'm using MS SQL Server) and executes the statement. Then it walks through the resultset getting the data from each field of every row. Finally, it builds the HTML page and sends it off to the client browser. While the database portion is not on the exam, it is an excellent example of how you can take advantage of the methods that are called by the container.

Servlet Synchronizing!

Servlets are run each in their own thread. When the synchronized keyword is used with a servlet's service() method, requests to that servlet are handled one at a time in a serialized manner. This means that multiple requests won't interfere with each other when accessing variables and references within one servlet. It also means the processing capabilities of the Servlet Container are reduced because the more efficient multithreaded mode has been disallowed for a given servlet that has been declared with the synchronized keyword.

Listing 4.16 is the servlet that queries the database based on the form data. Notice that you can forgo the above HTML file by appending the FirstName parameter to the URL like so: http://localhost:8080/examples/servlet/SearchLastNameServlet?LastName=Fuller. Also, you need to set up a data source with system data source names (DSNs), whether to a data source that is local to your computer or remote on the network.

Listing 4.16 Servlet That Queries a Database Based on Form Input from Listing 4.15

/* Don't use "java.io.*"
  Be explicit to see which classes are expected
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.ServletConfig;

public class SearchLastNameServlet extends HttpServlet
  //These will be used across requests,
  //so declare it at class level, 
  //not service or doGet level.
  //While it is common to use con,stmt,rs
  //I find these cryptic so I prefer to spell
  //them out completely for clarity.
  private Connection _connection = null;
  //Can differentiate between attributes of a class 
  //and local variables within a method 
  //with preceding underscore.
  private String _driverName = 
  //connects to Northwind DB in SQL Server on my machine
  private String _connectionString = 
  //optional, declare these in doPost() or service()
  //to avoid conflict between requests.
  private Statement statement = null;
  private ResultSet resultset = null;
  //not here, keep query local  
  //private String query = null;

  //common types
  final int COMMA = 1;
  final int TABLE_COLUMN = 2;
  final int TABLE_HEADER = 3;
  final boolean DELIMITED = true;

  //This is called only once during lifecycle!
  public void init(ServletConfig _config) 
   throws ServletException

    //warning! userid and password is exposed:
   String username = "sa";
   String password = "sa";

     //warning! userid and password is exposed:
     _connection = DriverManager.getConnection
      (_connectionString, username, password);
   } catch(Exception ex)
     throw new ServletException(ex.getMessage());

  public void service(HttpServletRequest _request, 
       HttpServletResponse _response) 
   throws ServletException, IOException

   String table = " Employees ";
   // query string where clause constraint
   String where = "";
   if (_request.getParameter("LastName").length() > 0) 
     String lastName = _
     where = " where LastName like \'";
     where += lastName;
     where += "%\'";
   } else
     where = "";
   StringBuffer htmlResult = new StringBuffer();
     String sqlQuery = "SELECT * from "+ table + where; 
     statement = _connection.createStatement();
     resultset = statement.executeQuery(sqlQuery);
      //Not necessary to place in array, but...
      String[] field = new String[8];
      //warning! these should be in same order as 
      //DB table field order
      //otherwise you can get errors, a Sun todo.
      field[0] = ""+resultset.getInt("EmployeeID");
      field[1] = resultset.getString("LastName");
      field[2] = resultset.getString("FirstName");
      field[3] = resultset.getString("Title");
      field[4] = ""+resultset.getDate("BirthDate");
      field[5] = resultset.getString("City");
      field[6] = resultset.getString("Region");
      field[7] = resultset.getString("Country");
      htmlResult.append( getTableBody(field) );
   } catch(Exception ex)
     throw new ServletException(ex.getMessage());

   StringBuffer html = new StringBuffer();
   html.append( htmlHeader() );

   //build results
   html.append( getTableHeader() );
   html.append( htmlResult.toString() );
   html.append( getTableFooter() );

   html.append( htmlFooter() );

   ServletOutputStream out = response.getOutputStream();
   out.println( html.toString() );

  public void destroy() 
    // Give connection to garbage collector
     connection = null;
   } catch(Exception ex)
     throw new ServletException(ex.getMessage());
  // convenience methods providing abstraction
  * Prints the table header.
  public String getTableHeader()
     StringBuffer header = new StringBuffer();

   header.append("<table border=\"2\">\n");
   header.append("<th align=\"left\">EmployeeID</th>\n");
   header.append("<th align=\"left\">LastName</th>\n");
   header.append("<th align=\"left\">FirstName</th>\n");
   header.append("<th align=\"left\">Title</th>\n");
   header.append("<th align=\"left\">BirthDate</th>\n");
   header.append("<th align=\"left\">City</th>\n");
   header.append("<th align=\"left\">Region</th>\n");
   header.append("<th align=\"left\">Country</th>\n");
    return header.toString();    

  * Prints the table body.
  public String getTableBody(String[] field)
   StringBuffer body = new StringBuffer();

   for(int index=0; index<field.length; index++)
     body.append("  <td align=\"left\">"); 
   return body.toString();    

  //you would bother to have a whole method for this
  //because someone might ask you to add extra
  //stuff to the bottom of every table so it is smart
  //to separate it like this.
  public String getTableFooter()
   StringBuffer footer = new StringBuffer();

   return footer.toString();    

  * Prints the html file header.
  public String htmlHeader()
   StringBuffer html = new StringBuffer();

   html.append("<title>LifeCycle Servlet Response" +
   html.append("<body bgcolor=\"#FFFFFF\"> ");
   html.append("<p align=center><h1>LifeCycle Servlet "+
         " Response</h1></p>"); 
   return html.toString();    

  * Prints the html file footer. 
  * This will change often due to 
  * marketing and lawyers.
  public String htmlFooter()
   StringBuffer html = new StringBuffer();

   html.append("<a href=\"http://localhost:8080/" +
     "examples/servlets/LifeCycle.html\">" +
   return html.toString();    

Once you set up a proper System DSN, or use a fully qualified connection string, the servlet will query the database. Listing 4.15 shows how you can create an HTML form to call this servlet. The output of the servlet query looks similar to Figure 4.6.

Figure 4.6 The result of a query by a servlet.

Listing 4.16 is just an example of when you might invoke the destroy() method. This code example could be improved in two ways. First, it is not thread-safe (statement and resultset variables could be local, not instance variables). That way separate instances wouldn't walk over each other's results. Second, this example doesn't make use of the Data Access Object pattern. You could do better by having separate objects for the Presentation and Database ("separation of concerns") portions of the program. I've lumped it all together here just to demonstrate the section point of how the destroy() method is used.

  • + Share This
  • 🔖 Save To Your Account