March 3, 2021
Hot Topics:

Understanding Servlets

  • By Steven Haines and Steven Potts
  • Send Email »
  • More Articles »

This is Chapter 21: Servlets from the book Java 2 Primer Plus (ISBN: 0-672-32415-6), written by Steven Haines and Steven Potts, published by Sams Publishing.

© Copyright Sams Publishing. All rights reserved.

Chapter 21: Servlets

You will learn about the following in this chapter:

  • What servlets are why you need them

  • How servlets work

  • How to set up a Jakarta Web server to run servlets

  • How to program servlets in Java

  • How to call other Java classes from inside servlets

  • How to maintain the state of a servlet using cookies in the user's browser

  • How to maintain the state of a servlet using a session on the server

When Java 1.01 was released, it was heavily oriented toward the development of applications that can run in a browser. The Applet architecture had received a lot of consideration and most of that release supported the GUI classes that facilitated their creation. Almost immediately, the question was asked, "What about developing for the server?"

The Java language offers much more to the developer than cool Internet graphics. It is a robust, highly object-oriented language that is easy to learn. It has a small footprint, and it can run on almost any computer that you can name. It is supported by a host of standard extensions that enables you to perform tasks, such as managing sound and video, without making you learn a host of proprietary command sets and scripting languages. It was only natural for Java to become popular on the server as well.

Java's presence on the server side was initially through programs called servlets. Servlets, like applets, are intended to run in a container. The servlet's engine is not called a browser, however, but a servlet container. Both applets and servlets have to be written to a pretty exact specification, but the servlets cannot have graphical user interfaces. They can, however, extract data from HTML forms, and they can create HTML and send it to the client to provide visual feedback.

With the introduction of the Java 2 Enterprise Edition (J2EE), servlets became only one of many server-side technologies available to programmers. Enterprise JavaBeans (EJB) have become popular for complex applications, but servlets remain as popular as ever.

In this chapter, we are going to cover servlets from the developer's standpoint. First, you will learn how to obtain and install a servlet container on your machine. Next, you will learn how to develop, deploy, and run servlets. Following that, you will learn how to write servlets that maintain user information across transactions.

What Servlets Are and Are Not

Servlets are miniature programs that must be run inside another program called a container. The container is responsible for brokering communication between the servlet and the outside world. Beyond that, servlets are like every Java application. They can import packages, write to the hard drive, and even install viruses on your machine. By default, servlets are trusted code. The reason is that if someone has enough permission on your computer to install a servlet, he already has enough power to tie the whole machine in knots anyway. The thought is that this installer is a trusted person, so the work that he does should be trusted, too.

Servlets are not Java applications. They must be run inside a container instead of from a command line. That being said, you can add almost any functionality available to a Java application to a servlet also.

Servlets are not the only way for the server to communicate with a browser. A Web server is an HTTP application. It receives communication via the HTTP protocol and it communicates with the browser via HTTP also. You can write your own HTTP server-side application that processes its own requests, bypassing both servlets and the servlet container. This chapter contains a simple example of how that is done.

Why Do I Need Servlets?

Servlets are here to make your life easier. If the only option available was to write HTTP applications from scratch every time new functionality was needed, not much development would take place on the Web. Not many organizations could afford to write HTTP programs from scratch. The existence of the servlet container avoids the cost of having to include the entire HTTP header processing code in every program. Servlets extend classes that take care of all that work behind the scenes.

Another advantage of servlets is that they scale nicely. The servlet container is responsible for instantiating your servlet whenever it is needed. If it is needed a lot, the servlet container has the option of creating as many threads or instances of your servlet as its load-balancing algorithms indicates it needs.

Servlets make good use of machine resources. They run in threads that are created by the servlet container. Each individual HTTP application program runs in its own process. Processes are far more expensive to create than threads, so the servlet approach is more efficient. Servlet containers can also pool connections so that the threads already created are reused instead of discarded. The ancestor of the servlet, the CGI program, lacked these features and has faded in popularity as a result.

How Servlets Work

Servlets are really parts of an application and require a servlet container to run. This servlet container is responsible for instantiating your servlet and calling the appropriate methods in the servlet at the appropriate times.

When you type the name of a servlet, you are really making a call to a program that is located on a server and not on your machine. At first, this process seems like magic, but after a little study you will see that this process only requires that each piece of software in the process perform a fairly simple set of tasks. Figure 21.1 shows this process graphically.

Figure 21.1.

The servlet container is responsible for instantiating your servlets.

  1. You type in the URL of a servlet that you want to call.

  2. The browser creates a request that contains the servlet and the name of your machine so that the server will know who to send feedback to.

  3. The server receives the request and hands it to the servlet container. The servlet container is a program that knows how to run servlets.

  4. The servlet container checks to see if any instances of this servlet are already in memory. If not, it loads an instance and runs the servlet's init() method.

  5. The servlet container waits for the init() method to finish. It then calls the service() method in your servlet from a new thread.

  6. The service() method calls the doGet() or doPost() method depending on what the request type is.

  7. A second user's browser requests that the same servlet be run on its behalf.

  8. The servlet container notices that an instance of the servlet is already in memory. So, it creates a new thread and starts running the same servlet that you are running.

  9. This new thread calls the service() method.

  10. If this is an HTTP servlet, the service() method calls the doGet() or doPost() methods.

  11. The first thread finishes and a response is sent to the Web server, which forwards it to your browser.

  12. The second thread finishes and a response is sent to the Web server, which forwards it to the second user's browser.

  13. At a certain point in the future, the servlet container decides to deinstantiate the servlet. At that point it calls the destroy() method once for each instance in memory.

Caution - Whether more than one instance of a single servlet is in memory depends on whether it is declared to be thread-safe. A servlet is assumed to be thread-safe unless it implements the SingleThreadModel interface. If it implements this interface, a new instance will be created for each simultaneous access. This has serious performance penalties associated with it, so it should only be done if absolutely necessary.

Setting Up a Web Environment

Before you can develop and test servlets, you need to set up a Web development environment. You will need several pieces of software to accomplish this. The first one is a recent version of Java, which you probably already have installed on your machine. In case you don't, however, you can obtain the Java Software Development Kit (SDK) from Sun Microsystems at http://www.java.sun.com.

You most likely have a browser installed on your machine also. You will want to make sure that you have an up-to-date browser version, so it would be a good idea to check this version against the latest release that is available on the Microsoft and Netscape Web sites. There are times when the two leading browsers behave differently, so it is also a good idea to install both of them on your machine for testing.

In addition, you need some way to compose and edit programs. All the examples in this chapter can be typed in using Notepad or vi and run from a command line.

Note - Java-specific editors are available, and you might find that it is worth your while to learn how to use one. Forte has a version that is available for free at http://www.java.sun.com. JBuilder and Visual Café are two commercial products that are popular with developers also.

The third piece of the servlet puzzle is the servlet container itself. If you are currently running a Web server that provides servlet support, you can skip this step. If you don't have a servlet container running already, you will need to follow the instructions in the next section to set up the Tomcat server on your machine. Tomcat contains a light version of a Web server that is complete with a servlet container.

Installing Jakarta Tomcat

Jakarta Tomcat is available at no cost from the Apache Web site at http://www.apache.org/.

The link for Tomcat 4.0.4 is


Choose a release that is right for your needs. If you are running Java 1.4, the following self-extracting .exe file will be correct for you:


Caution - As new versions of Tomcat are released, the links that lead to them will differ from those shown previously. In these cases, you will need to go to the http://jakarta.apache.org/ Web site and navigate to the newest release.

You will then be prompted to enter the location where you want this .exe file stored. Next, open Windows Explorer and double-click the name of the .exe file. This will open an installation wizard that will guide you through the installation. After you answer a few questions, you will be told that the installation is complete.

If you are running under Unix, you can download the tar version and follow the instructions on the Apache Web site on how to install Tomcat on your machine.

Caution - Vendor Web sites change from time to time. If the previous steps don't work exactly, look for similar links at each step, and you should be able to succeed in getting Tomcat installed.

Starting Tomcat

You start Tomcat by opening a command window and typing the following command.

java -jar -Duser.dir="C:\Program Files\Apache Tomcat 4.0" 
"C:\Program Files\Apache Tomcat 4.0\bin\bootstrap.jar" start

Tomcat will output several lines of responses like these, which provide feedback that the server is really running.

Starting service Tomcat-Standalone
Apache Tomcat/4.0.4
Starting service Tomcat-Apache
Apache Tomcat/4.0.4

On some operating systems, the installation script places some shortcuts in your file system to make the task of starting Tomcat easier. On our test machine, Windows XP, these shortcuts were placed in a directory called:

C:\Documents and Settings\Your Name\Start Menu\Programs\
   Apache Tomcat 4.0

Your Name will be replaced by the login name of the machine that you are using.

Another link on that page opens a browser that contains the root page for the copy of the Tomcat documentation that is stored on your local hard drive. Figure 21.2 shows this page.

Figure 21.2

The Tomcat documentation provides detailed instructions about how to get the server and keep it running.

Note - You can find answers to many of your questions with these pages, so it would be a good idea to bookmark the root page in your browser.

Page 1 of 9

This article was originally published on April 8, 2003

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date