Servlets vs. CGI

HTTP Basics

HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request, the web server responds, and the transaction is done.

When the client sends a request, it first specifies an HTTP command, called a method, that tells the server the type of action it wants performed. The first line of the request also specifies the address of a document (a URL) and the version of the HTTP protocol it is using. For example:

GET /intro.html HTTP/1.0
This request uses the GET method to ask for the document named intro.html

After sending the request, the client can send additional information about the request, called headers, such as what software the client is running and what content types it understands. Example request headers:

accept-language: en-us
user-agent: Mozilla/4.0 (compatible: MSIE 5.01; Windows NT 5.0)
accept-encoding: gzip, deflate

After the headers, the client sends a blank line, to indicate the end of the header section. The client can also send additional data, if appropriate, as it is with the POST command.

After the client sends the request, the server processes it and sends back as response. The first line of the response is a status line that specifies the version of the HTTP protocol the server is using, a status code, and a description of the status code. For example

HTTP/1.0 200 OK
Another common status code is 404, with the description Not Found.

After the status line, the server sends response headers that tell the client what software the server is running and the content type of the server's response. For example

MIME-version: 1.0
Content-type: text/html
Content-length: 1029
The server sends a blank line after the header to conclude the header section.

GET and POST

The GET method was intended for reading information (such as files), but it can include additional information about the request. This information is appended to the request URL as a query string. Placing the additional information in the URL allows the page to be bookmarked.

The POST method passes its information directly over the socket connection as part of its HTTP request body.

There are several other lesser-used HTTP methods. The HEAD method is used when the client wants to see only the headers of the response, perhaps to determine the document's size or modification time. The PUT and DELETE methods allow the client to place or delete documents on the server.

Servlet Structure

public class ExampleServlet extends HttpServlet {

   public void doGet( HttpServletRequest req,
                      HttpServletResponse res )
      throws ServletException, IOException
   {
      PrintWriter out;

      res.setContentType( "text/html" );
      out = response.getWriter();

      // create and send HTML page to client
   }
}

Common arguments for setContentType are text/html for HTML documents and text/plain for ordinary preformatted text documents.


Maintained by John Loomis, last updated 5 Jan 2001