By Rick Scott

If your concept of Java is still applets in a browser, turn your attention to the server instead. Learn to develop server-side Java, and you’ll stand well poised to create some truly useful client-server Java applications: form processors, database queriers, persistent shopping carts, smart surveys, guestbooks, counters, and more. In fact, if you’re apprehensive of client-side Java—a somewhat well-grounded position—use whatever you like on the client side and run Java on the server alone.

Servlets are to Web servers what applets are to browsers: Java programs that extend built-in server/browser functionality. Unlike applets, servlets have no GUI, because they execute on the server side, behind the scenes, where they respond to client requests. Though not formally tied to any one specific client-server protocol, servlets are most often used with HTTP, the protocol that drives the Web.

Using Java servlets nudges CGI out of the client-server loop. Since CGI is such a trusted technology, you may wonder if this is a smart thing to do. So let’s first look at the pros and cons of using Java servlets instead of CGI scripts.

Servlets vs. CGI scripts
As most developers realize, the advantages of CGI technology are many. Not only has it been around forever and is tried and true, but scads of good CGI scripts exist online for the plucking. Most every Web server speaks some dialect of CGI, and almost all ISPs offer some level of CGI user support. So why should you even consider forsaking CGI for Java servlets?

The following chart compares and contrasts Java servlets with CGI scripts. Scores in each category range from very low to very high. Note that the picture this chart paints is, to some extent, subjective, since there are no hard-and-fast scoring rules in most categories. With that grain of salt, here are the comparisons:

Java servlets CGI Scripts

Ease of creation


Depending on their degree of functionality, Java servlets, like Java applets and applications, can be quite challenging to code. However, the basic model for servlets (as discussed on the next two pages) is a refreshingly simple and straightforward one. Tons of excellent Java IDEs exist, making your job as servlet creator potentially much easier. Again, bare-bones CGI scripts are really quite simple to code, but the difficulty increases exponentially with higher functionality. Since CGI is a specification (for data exchange) rather than a language, you can leverage your existing programming skills by coding CGI scripts in your language of choice: Perl, C/C++, Tcl, Visual Basic, and, yes, even Java.

Execution efficiency


A servlet runs in a single process (within the server process). Thus, unlike CGI scripts, a new process does not have to be spawned for each new request for the servlet. This makes for low execution overhead and high efficiency. It also enables a servlet to handle multiple concurrent requests with ease and elegance. Moreover, since there is only a single instance of the servlet in existence (all concurrently running instances are actually threads of the main instance), server memory drain is minimized, and data persistence is enabled. A CGI script often spawns a new process every time it is invoked, thus causing a noticeable lag in transfer speed and potentially consuming great gobs of server processing time and resources. I say “often” because there are CGI technologies, such as FastCGI, that minimize script-invocation overhead. But even the best of these does not provide as effective of a solution as the one deployed by Java servlets.



Servlets can be supported on a large number of popular Web servers, but not all ISPs offer this support. CGI scripts can be, and are, supported by the great majority of existing Web servers. Harder to come by are ISPs that will allow users to upload their own custom CGI scripts (for obvious security reasons, since CGI scripts, like Java servlets, have the power to wreak system havoc).

Platform independence

Very high

After all, we are talking about Java here: “Write once, run anywhere.” Perl, when coded correctly, is almost completely platform independent. However, many other CGI-capable languages (such as Visual Basic) are not.



Online servlet repositories exist, but their number and breadth/depth of offerings do not rival those of CGI script repositories. Online CGI script repositories abound. From these, you can acquire custom CGI scripts to upload to your server. Or, if your server won’t let you install custom scripts, you can take advantage of the many remotely hosted CGI scripts out there.



The strict Java servlet security model (Security Manager) and servlet sandbox safeguard your system from both intentional and accidental malicious servlet behavior. The mechanism of trusted (digitally signed) servlets allows for increased servlet capabilities. Since CGI scripts are not subject to the same degree/granularity of security sandboxing as Java servlets, they are significantly less secure.

Trouble deciding?
If you’re comfortable programming in Java and your Web server supports servlets, go with servlets instead of CGI scripts, particularly if your application will be getting a large number of concurrent hits. Also, since servlets can avail themselves of all the standard Java API goodies, they are better than CGI scripts for large-scale server-side applications. And finally, if security is critical, stick with servlets.

If, on the other hand, Java is not your cup of tea, your Web server is servlet-shy, or you’ve found the perfect Perl script to tweak a bit and upload, go with the CGI.

There are of course other server-side technologies in use today: JSP (Java Server Pages, which extend servlets), ASP (Active Server Pages, on Microsoft servers), SSI (server-side includes), PHP, Python, server-side JavaScript, and more. JSP and ASP are competing behemoths and beyond the scope of this article, while the other languages are either significantly less powerful (SSI) or not as widely used (server-side JavaScript) as Java servlets and CGI scripts.

Creating servlets
Before you can successfully compile a Java servlet, you must ensure that your computer is properly set up and configured. This might be a nontrivial task, but once it’s done, it’s done. Servlet support is built into the Java 2.0 Platform, Enterprise Edition 1.3 SDK. If your computer can’t support it, or you don’t want to install the entire J2EE, you can also extend the Java 2 SDK Standard Edition to support servlets. Either put theservlet.jar file from Jakarta in the directory jre/lib/ext or install the Java Servlet Development Kit (JSDK) from Sun’s archive. For the JSDK, make sure its jsdk2.1server.jar and jsdk2.1server.jar files are added to your system’s classpath.

Servlet architecture
At its most basic, a servlet is an instance of a Java class that implements thejavax.servlet.Servlet interface. Most servlets do this indirectly, by extending javax.servlet.http.HttpServlet or javax.servlet.http.GenericServlet, two of javax.servlet.Servlet’s standard implementations. Thus the hierarchy looks like this:
Servlet -> HttpServlet|GenericServlet -> MyServlet

Servlet life cycle
The life cycle of a servlet is very simple, consisting of three primary methods:

  • ·        init() begins the servlet life cycle and initializes servlet settings. A servlet’s init() method is called once—and only once—each server session, the very first time the servlet is called during that session.
  • ·        service() reads the incoming client request and generates an appropriate servlet response back to the client. service() is typically called many times during a servlet’s life cycle, once for each client request.
  • ·        destroy() ends the servlet life cycle and cleans up shop. destroy() is called once, just before the server session ends (in other words, before the server is shut down).

Since init() and destroy() are each called only once during a servlet’s life, a typical servlet life cycle would look like this:
init(), service(), service(), service(), service(), …, service(), destroy()

When a servlet gets called by a client (browser), it receives two object arguments:

  • ·        A ServletRequest object, which contains salient information from the client to the server: names of the parameters sent by the client, the network protocol used by the client, names of the host that made the servlet request and the server that received it, and so on.
  • ·        A ServletResponse object, which contains information from the servlet back to the client: an output stream and accompanying object via which the servlet can send the reply data, and this data’s length and MIME type.

The “Hello, client!” servlet
Time to roll up your sleeves and code the mandatory first program in any new technology: “Hello, world!” or, in this case, “Hello, client!” This tiny servlet simply sends an HTML page with the H1 heading “Hello, client!” back to the requesting client browser.

The complete “Hello, client!” code, with copious comments

If you want to compile it on your own, copy and paste it into a text file and save it as

We begin with the required Java class imports:
import javax.servlet.*;
import javax.servlet.http.*;

Good* provides the required IOException object (see below), javax.servlet.* provides the ServletException object, and javax.servlet.http.* provides the HttpServletRequest and HttpServletResponse objects, the doGet() and setContentType() methods, and so forth.

Next, we define the HelloClient class, which is the only class in this servlet:
public class HelloClient extends HttpServlet {

All Java servlets implement thejavax.servlet.Servlet interface. Many servlets, ours included, implement Servlet indirectly by extending the javax.servlet.http.HttpServlet class, which in turn implements Servlet directly.

TheHelloClient class contains but a single lonely method, doGet():
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

doGet() is a public void method that accepts two arguments, the all-important client/servlet input/output objects: HttpServletRequest request and HttpServletResponse response. (For more information on these objects, see the previous page.) doGet() can throw two exceptions: ServletException (thrown when the servlet encounters any difficulty) and IOException (thrown when an I/O problem of any sort occurs).

The body ofdoGet() consists of these four statements:
PrintWriter out = response.getWriter();
 “<html>” +
 “<head><title>Hello, client! servlet</title></head>” +
 “<body><h1>Hello, client!</h1></body>” +

ThesetContentType() method specifies the content (MIME) type of the response object that the servlet sends back to the client. In this case we set the MIME type to “text/html” since we are sending an HTML document to the client. setContentType() can also be used to specify character encoding, but in this case, we’ll accept the default encoding.

getWriter() returns out, an object of type PrintWriter that you use to send content (again, HTML in our case) to the client.

out.println(String s) writes a string to the client, followed by a carriage return/line feed combo. out.close() flushes/closes the out stream.

Just as with any normal Java applet or application, at this point you compile the source code to a bytecode class file. And that’s about all there is to it.

Deploying servlets
Deploying means uploading and installing the servlet on your Web server, so that it can be successfully called from a client browser. Doing this for the first time might be a bit traumatic, depending on your server’s current support (or lack thereof) for Java servlets.

To deploy a servlet on your ISP’s Web server, find out whether it is configured to support Java servlets. If so, read up on the system policy for installing servlets—directory/size/security restrictions and so on—then upload away! If not, request (beg?) your ISP to add Java servlet support to its already impressive list of client services.

Installing servlet support on your own server entails platform dependencies beyond the scope of this article; look to for guidance. If you do have servlet support, your configuration will determine into what directory you’ll upload your class file, and whether the.class extension is necessary in any URL pointing to it. You execute the servlet by requesting that URL, whether in a link, form action, or other HTTP request device.

Congratulations! You are now steeped in the basics of Java servletdom—the hows and whys of servlets, the pros and cons of servlets vs. CGI scripts, and the rudiments of servlet programming and deployment.