Editorial Reviews
bn.com
The Barnes & Noble Review
If you're a Java programmer, why reinvent the wheel? By now, someone has created elegant solutions for many of the most troublesome problems you're likely to face. That someone is Ian Darwin, whose Java Cookbook offers nearly 900 pages of rip-and-run code snippets, covering everything from regular expressions to RMI, from data structures to servlets.
Darwin's modeled his book on O'Reilly's legendary Perl Cookbook. That's a very high standard he's set for himself -- and he's lived up to it. His range is extraordinary and includes plenty of examples for the hottest areas of Java development.
Working with XML for the first time? You'll find concise, easy-to-borrow code for the tasks you'll need to perform right away: parsing XML with SAX and/or DOM, verifying structure, generating new XML, and transforming XML with XSLT. Building server-side web apps? There's code for setting cookies, tracking sessions, presenting dynamic pages, even generating PDF from a servlet. (In this chapter, Darwin even throws in Java code for a skeleton "news portal" site, à la Slashdot.)
Java Cookbook contains practical solutions for areas of Java you may have barely touched. Need to mail-enable your apps? Work more effectively with threads? Call Java from native code? Use introspection? Internationalize your software? Read or write compressed files? Make the most of Java's underutilized pattern-matching capabilities? It's all here. If you don't have time to waste, waste no time getting Java Cookbook.
(Bill Camarda)
Bill Camarda is a consultant, writer, and web/multimedia content developer with nearly 20 years' experience in helping technology companies deploy and market advanced software, computing, and networking products and services. His 15 books include Special Edition Using Word 2000 and Upgrading & Fixing Networks For Dummies®, Second Edition.
Show More
Read an Excerpt
Chapter 18: Web Server Java: Servlets and JSP
Introduction
This chapter covers Web Server Java, but you won't find anything about writing CGI programs in Java here. Although it would be entirely possible to do so, it would not be efficient. The whole notion of CGI programs is pretty much passe. Every time a CGI program is invoked, the web server has to create a new heavyweight process in which to run it; this is inefficient. If it's interpreted in Java, the program has to be translated into machine code each time; this is even more inefficient.
Today's trend is toward building functionality into the web server: Microsoft ASP, PHP3, Java servlets, and JavaServer Pages? (JSP1) are examples of this. None of these normally requires a separate process to be created for each request; the Java-based solutions run in a thread (see Chapter 24) inside the web server, and the Java bytecode need only be translated into machine code once in a long while, assuming a just-in-time (JIT) runtime system. Naturally, this book concentrates on the Java solutions.
We'll use two examples in this chapter. Consider the task of displaying a web page with five randomly chosen integer numbers (lottery players love this sort of thing). The Java code you need is simple:
// Part of file netweb/servlets_jsp/FiveInts.java
Random r = new Random( );
for (int i=0; i<5; i++)
System.out.println(r.nextInt( ));
But of course you can't just run that and save its output into an HTML file because you want each person seeing the page to get a different set of numbers. If you wanted to mix that into a web page, you'd have to write code to println( )
a bit of HTML. This would be a Java servlet.
The servlet code could get messy, however, since you'd have to escape double quotes inside strings. Worse, if the webmaster wanted to change the HTML, he'd have to approach the programmer's sanctified source code and plead to have it changed. Imagine if you could give the webmaster a page containing a bit of HTML and the Java code you need, and have it magically compiled into Java whenever the HTML was changed. Imagine no longer, says the marketer, for that capability is here now, with JavaServer Pages.
The second example is a dictionary (list of terms); I'll present this both as a servlet and as a JSP.
I won't talk about how you get your servlet engine installed, nor exactly how you install your servlet. If you don't already have a servlet engine, though, I'd recommend downloading Tomcat from http://jakarta.apache.org. Tomcat is the official reference implementation--so designated by Sun--for the servlet and JSP standard. It is also (as you can infer from the URL) the official servlet engine for the ever-popular Apache web server.
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....
Read More