First Servlet: Generating an HTML Page

Discussion

The abstract class javax.servlet.Servlet is designed for those who wish to
structure an entire web server around the servlet notion. For example, in
Sun's Java Web Server, there is a servlet subclass for handling plain HTML
pages, another for processing CGI programs, and so on. Unless you are writing
your own web server, you will probably not extend from this class, but rather
its subclass HttpServlet, in the package javax.servlet.http. This class has a method:

The service method is passed two arguments, request and response. The request contains all the information about the request from the browser,
including its input stream should you need to read data. The response argument
contains information to get the response back to the browser, including the
output stream to write your response back to the user.

But the web has several HTTP methods for passing data into a web
page. Unimportant for plain HTML pages, this distinction becomes of interest
when processing forms, i.e., web pages with fill-in-the-blank or choice items.
Briefly, the GET method of HTTP is used to pass all the form data appended to
the URL. GET URLs look like this, for example:

http://www.acmewidgets.com/cgi-bin/ordercgi?productId=123456

They have the advantage that the user can bookmark them,
avoiding having to fill in the form multiple times. But there is a limit of
about 1KB on the overall length of the URL. Since this must be a single
string, there is an encoding that allows spaces, tabs, colons, and other
characters to be presented as two hexadecimal digits: %20 is the character hexadecimal 20, or the ASCII space character. The POST method, by contrast, passes any parameters as input on the socket connection, after the HTTP headers.

The default implementation of the service() method in the HttpServlet class figures
out which method was used to invoke the servlet. It dispatches to the correct
method: doGet( ) if a GET request, doPost( ) if a POST request, etc., passing along the
request and response
arguments. So while you can, in theory, override the
service( ) method, it's more common (and officially
recommended) to override either doGet( ),
doPost( ), or both.

Several servlet engines (e.g., Allaire JRun) generate a lot of very small log files spread over many different directories. It is worth investing the time to learn where your particular servlet engine records stack traces, standard error and output, and other messages.

See also recipe 16.5, which shows how a servlet or other server component can communicate with a network-based logging tool.

You can do much more with servlets. Suppose you wanted to print a dictionary -- a list of terms and their meanings--from within a servlet. The code would be pretty much as it was in Figure 18-1, except that you'd need a doGet( ) method
instead of a doPost( ) method. Example
18-2 is the code for TermsServlet.