XA
ASERT LOGO Advanced Software Engineering, Research and Training
Allowing Secure Applications to be Rapidly Developed and Deployed

An Introduction to Java Server PagesT and ServletsT

PART I: An Introduction to Servlets
Author: Danielle Danielsson
Last Revised: 1st February 2001

1.1 Servlets and how not to bring your web server to its knees

Before talking about web server orthopedics, weak knees and all, we need first to answer the very fundamental question of "What are servlets?" In short, servlets are everything that Java applets promised, but never quite delivered, at least not on the client side. In other words, servlets are Java applets without the sexy GUI, but all the muscle that the Java API provides. How is this nirvana achieved? By moving the focus of application development onto the server side.

With servlets, developers finally have the freedom that full control of the server provides, and the freedom from the unpredictabilities of the client's environment - the Java Virtual Machine version installed, sufficient RAM, and browser compatibilities. This is especially true when endeavouring to deliver applications to the diverse Internet audience. This may be less of an issue on the corporate Intranet where user PC's are required to conform to a standard operating environment, although I have yet to see a true SOE in a large corporation or government department.

Servlets are indeed a replacement for the Common Gateway Interface, CGI, that has been the mainstay of web servers for many years. Scripts written in a plethora of languages from PERL to Python, and from Tcl/Tk to Rebol, provided a means of delivering dynamic web pages. They connected to databases, accepted and responded to form submissions, and performed a whole host of other server side work. Very effectively so, as long as there were not too many simultaneous requests which spawned process after process that in the end brought the server to its knees, depleted of resources. At this point the unaware user submitting that final fateful query which sapped the server of its strength, was delivered an "500 server error". Only the server administrator could re-animate the server again by rebooting which released the tied up resources. The difficulty in maintaining state, the high overhead in continuously re-establishing of connections to the database during a client's session, and the resulting performance impact, made CGI ripe for a replacement.

Since the web has become a mission critical tool for enterprises to keep in contact with their clients and deliver services and products, it is no longer acceptable for a web server to go down. This is where servlets come in.

Some of the capabilities that make servlets the ideal replacement for CGI are as follows:

  • They are multi-threaded: one servlet can handle multiple clients simultaneously; unlike CGI scripts where a new process is generated for each incoming client request.
  • A servlet is instantiated once: it is loaded into memory and only removed if programmatically instructed or the web server is stopped, hence it does not need to be re-loaded every time a request comes in, as in the case of CGI where the script interpreter must first be loaded for each request thereby reducing performance;
  • Servlet initialization at start-up: it is here where resource intensive processes can be set in motion and can then become available to multiple clients throughout the life of the servlet;
  • Being based on Java, servlets are extensible and scaleable: extensible because a large and complex application can be constructed over time with any number of servlets; and scalable because the Java Virtual Machine is capable of taking advantage of multiple processors if available.

1.2 Anatomy of a Servlet

Now that we are thoroughly convinced of the servlets benefits to us, let's take a gander at the guts of a fairly plain, unassuming and modest servlet.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class MyAnatomy extends HttpServlet
{
    /**
     * The init method initializes, for example, a connection to database;
     * or actions that need to be carried out only once during the life of
     * a servlet and be available to many clients simultaneously.
     * We will modify this in a later tutorial when a database
     * connection is created.
     */
    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
    }

    /**
     * The service method is where variables should be initialized if each
     * client needs to receive its own instance of the variable.
     */
    protected void service(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        // Create the HTML for output to the browser
        String pageText = "<html>";
        pageText += "<head><title>MyAnatomy Servlet</title></head>";
        pageText += "<body>";
        pageText += "<p>All great journeys start with one small step.</p>";
        pageText += "<body><HTML>";

        // Content type to alert the browser to expect text or html.
        response.setContentType("text/html");

        // Use getWriter() to send a character stream to the client browser
        PrintWriter out = response.getWriter();

        out.println(pageText);
        out.flush();
        out.close(); // close PrintWriter stream
    }

    /** Use this method to obtain information about the servlet */
    public String getServletInfo() {
        return "Hi, I'm called My Ana Tomy!";
    }

    /**
     * This is called by the servlet container to inform the
     * servlet that it will be taken out of service, for example
     * when the web server is stopped or the servlet is reloaded.
     */
    public void destroy() {
        // Add code here to release any resources previously allocated
        // in the init method. The use of destroy() will be demonstrated
        // in a later tutorial.
    }

}

 

Walter says: if you need to do any initialisation in your servlet, place the appropriate code in the init(...) method rather than in the normal class Constructor. Place your code directly after the call to super.init(...).

1.3 The basics of a Servlet

A class is identified as a servlet if it implements the javax.servlet.Servlet interface. The Servlet API provides two ready-made classes that are available: the GenericServlet and HTTPServlet. In the above example we have chosen to extend the HTTPServlet.

The most commonly extended class is HTTPServlet which provides, as the name suggests, HTTP specific functions. When extending HTTPServlet, it is necessary to override at least one of these HTTP functions, which are shown below:

  • doGet - This method is used in some form handling processes where caching is required eg submissions to search engines. Usually overridden.
  • doPost - This method is used in handling forms submissions when caching is not desireable. It is usually overridden.
  • doPut - Used in client request for storing a file on the server; not normally used due to security issues.
  • doDelete - Used in client request for deleting a file from a server; not frequently used due to security issues.
  • init and destroy - almost always overidden
  • service - rarely overridden, accept default
  • doOption - Returns to the client information about the HTTP options supported by the server. Rarely overridden, accept default
  • doTrace - Returns request header information. Often used in debugging. Rarely overridden, accept default

Each of these methods have the following parameters:

  • HTTPServletRequest - this provides the servlet with an input stream to read data from the client;
  • HTTPServletResponse - this object provides the servlet with an output stream to send data to the client.

GenericServlet is a class that is protocol independent and would normally be extended if the need arose to code for non-HTTP protocols.

In Part 1 of this series of tutorials we only covered the very basics of servlets. Since we now know what a servlet is, we'll be able to identify one if it is encountered in a dark alley. Subsequent tutorials will exercise the Servlet API a little more as we develop a real life, web based phone book with a database backend. We'll get to know JSP's and why we would want to use them; we'll learn about how to establish communication between a Servlet and a database and how to deliver the results to the requesting client.

To prepare for the remaining parts of this tutorial, and if you don't already have a Servlet and JSP development environment, please see the appendix for some resources to get you started.

See you again in Part 2!

Appendix

Setting up your development environment by downloading or ensuring that you have these packages installed on your machine:

  1. JavaT 2 SDK, Standard Edition, v 1.3
  2. J2EET SDK
  3. JavaServer Web Development Kit (JSWDK) 1.0.1: is the reference implementation for JSP and the JavaT Servlet API. This release of JSWDK supports JSP 1.0 and the Servlet API 2.1. Alternatively I would recommend JRun.
  4. JRun 3.0: Free download of the developer edition, supporting:
    • Enterprise JavaBeans 1.1
    • Java Transaction API 1.0
    • Java Messaging Service 1.0
    • Java Server Pages 1.1
    • Java Servlets 2.2