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

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

<p align=center>
<h1>LifeCycle Demonstration Using DB</h1>
<form name="formSearch" method="post" action=
"localhost:8080/examples/servlet/SearchLastNameServlet">
<table border="0" cellspacing="0" cellpadding="6">
  <tr>
   <td><h2>Search</h2></td>
   <td></td>
  </tr>
  <tr>
   <td><b>Last Name</b></td> 
   <td><input type="text" name="LastName" 
         value="Fuller">
   </td> 
  </tr> 
  <tr> 
   <td></td>
   <td align="center"><input type="submit" name="Submit"
     value="Submit">
   </td> 
  </tr> 
</table>
</form>
</p>
</body>
</html>

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 = 
              "sun.jdbc.odbc.JdbcOdbcDriver";
  //connects to Northwind DB in SQL Server on my machine
  private String _connectionString = 
                  "jdbc:odbc:employeeDB";
  //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
  {
   super.init(_config);

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

   try
   {
     Class.forName(_driverName);
     //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
  {
   _response.setContentType("text/html");

   String table = " Employees ";
   // query string where clause constraint
   String where = "";
   if (_request.getParameter("LastName").length() > 0) 
   {
     String lastName = _
             request.getParameter("LastName");
     where = " where LastName like \'";
     where += lastName;
     where += "%\'";
 
   } else
   {
     where = "";
   }
   
   StringBuffer htmlResult = new StringBuffer();
   try
   {
     String sqlQuery = "SELECT * from "+ table + where; 
     statement = _connection.createStatement();
     resultset = statement.executeQuery(sqlQuery);
  
     while(resultset.next())
     {   
      //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() 
  {
   try
   {
    // Give connection to garbage collector
     connection.close();
     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("<tr>\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");
   header.append("</tr>\n");
    return header.toString();    
  }

  /*
  * Prints the table body.
  */
  public String getTableBody(String[] field)
  {
   StringBuffer body = new StringBuffer();
   body.append("<tr>\n");

   for(int index=0; index<field.length; index++)
   {
     body.append("  <td align=\"left\">"); 
     body.append(field[index]); 
     body.append("</td>\n");
   }
   body.append("</tr>\n");
   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();

   footer.append("</table>\n");
   
   return footer.toString();    
  }

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

   html.append("<html>");
   html.append("<head>");
   html.append("<title>LifeCycle Servlet Response" +
         "</title>");
   html.append("</head>");
   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\">" +
     "</b>BACK</b></a>");
   html.append("</p>");
   html.append("</body>");
   html.append("</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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020