Web Server Java -- Servlets and JSP
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
First Servlet: Generating an HTML Page
Problem:
You want a servlet to present some information to the user.
Solution:
Override the HttpServlet method service( ), or doGet( )/doPost( ).
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:
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException;
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.
The simplest HttpServlet is something
like Example 18-1.
Example 18-1: HelloServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple Hello World Servlet
*/
public class HelloServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter( );
response.setContentType("text/html");
out.println("<H1>Hello from a Servlet</h2>");
out.println("<P>This servlet ran at ");
out.println(new Date().toString( ));
out.println("<P>Courtesy of HelloServlet.java 1.2 ");
}
}
The program will give output resembling Figure 18-1.
|
|
Debugging Tip for Servlets 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.
Example 18-2: TermsServlet.java
/** A Servlet to list the dictionary terms.
*/
public class TermsServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter( );
out.println("<HTML>");
out.println("<TITLE>Ian Darwin's Computer Terms and Acronyms</TITLE>");
out.println("<BODY>");
out.println("<H1>Ian Darwin's Computer Terms and Acronyms</h2>");
out.println("<TABLE BORDER=2>");
out.println("<TR><TH>Term<TH>Meaning</TR>");
// This part of the Servlet generates a list of lines like
// <TR> <TD>JSP <TD>Java Server Pages, a neat tool for ...
TermsAccessor tax = new TermsAccessor("terms.txt");
Iterator e = tax.iterator( );
while (e.hasNext( )) {
Term t = (Term)e.next( );
out.print("<TR><TD>");
out.print(t.term);
out.print("<TD>");
out.print(t.definition);
out.println("</TR>");
}
out.println("</TABLE>");
out.println("<HR></HR>");
out.println("<A HREF="servlet/TermsServletPDF">Printer-friendly (Acrobat PDF) version</A>");
out.println("<HR></HR>");
out.println("<A HREF="mailto:compquest@darwinsys.com/subject=Question
">Ask about another term</A>");
out.println("<HR></HR>");
out.println("<A HREF="index.html">Back to HS</A> <A HREF="../
">Back to DarwinSys</A>");
out.println("<HR></HR>");
out.println("<H6>Produced by $Id: TermsServlet.java,v 1.1 2000/04/06
ian Exp $");
out.print(" using ");
out.print(tax.ident);
out.println("</H6>");
}
}
