Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Java 1.2 Unleashed

Java 1.2 Unleashed -- Ch 47 -- Sun's Java Web Server

Java 1.2 Unleashed

Previous chapterNext chapterContents

- 47 -

Sun's Java Web Server

In Chapter 32, "Server Programs," you learned how to write server programs in Java. You saw how easy it is to listen for incoming connections, read requests from the connection's input stream, process the requests, and write responses to the connection's output stream. JavaSoft also realizes that it has a winner in Java when it comes to server development and server-side programming, and has developed the JavaServer Toolkit and Service API. The JavaServer Toolkit is a server framework from which other servers can be developed. One of the servers developed from this framework is the Java Web Server, formerly named Jeeves. Jeeves doesn't stand for anything--it's the name of a butler (and hence a SERVant).

One of the key features (among many) of the JavaServer Toolkit is its support for Java server-side programming in the form of servlets. Servlets are the server-side analog to applets. JavaSoft has developed a Servlet API for servlet programming. This API is a standard extension to JDK 1.2.

In this chapter, you'll install Java Web Server and learn how it works. You'll learn about servlets, cover the basics of the Servlet API, and develop a few servlets of your own. When you finish this chapter, you'll be able to use Java Web Server and servlets to build advanced Web sites.

What Are the JavaServer Toolkit and Java Web Server?

The JavaServer Toolkit is a framework for building Internet and intranet servers. It implements the functions that are common to many servers:

Besides providing these basic server functions, the Java Server Toolkit makes it easier to integrate the following advanced capabilities into the servers you develop:

The JavaServer Toolkit provides a framework for developing Java-based server software. This framework was used to develop Java Web Server. Java Web Server is a top-of-the-line, fully HTTP 1.1-compliant Web server that provides a number of attractive features:

Of these features, this chapter will focus on the development of Java servlets. Information on other Java Web Server capabilities is covered in the server documentation.

How Does Java Web Server Work?

Because Java Web Server is built using the Java Server framework, it follows its basic execution paradigm. An acceptor listens for incoming connection requests on the TCP ports managed by the server. It hands off accepted connections to connection handlers. The connection handlers receive HTTP requests from Web server clients and load and invoke servlets to process the HTTP requests. Figure 47.1 provides an overview of Java Web Server's operation.

FIGURE 47.1. How Java Web Server works.

What's unique about the Java Server Toolkit, in general, and Java Web Server, in particular, is the use of servlets. Servlets are server extensions that are written in Java and are associated with particular URLs. When a request for the URL of a servlet is received from a Web browser, Java Web Server invokes the servlet to process the request. Java Web Server provides the servlet with all the information it needs to process the request. It also provides a mechanism for the servlet to send response information back to the Web browser. The Servlet API (covered later in this chapter in the section "The Servlet API") is used to develop servlets. Servlets can be preloaded by Java Web Server or loaded on-the-fly as they are needed.

Installing Java Web Server

In order to run the examples in this chapter, you'll need to download and install Java Web Server. It is available from JavaSoft at Java Web Server for Windows 95 and NT is distributed as a self-extracting executable file. Run the file and follow the installation instructions to install Java Web Server on your system.

Running Java Web Server

Java Web Server comes with extensive documentation that describes its features and shows how they work. I'm not going to duplicate the documentation here, but I will give you enough information to get you up and running and to show you how to develop and use servlets.

To start Java Web Server, open a DOS window, change to Java Web Server's bin directory, and run httpd, as follows:


NOTE: If you installed Java Web Server as a service under Windows NT, it is automatically started when you reboot your machine.

Java Web Server provides Web service on port 8080 as a default. This lets you use Java Web Server without having to stop your current Web server (if any). I've temporarily installed Java Web Server on a host named Figure 47.2 shows the server's default Web page, located at

FIGURE 47.2. The Java Web Server default Web page.

The default Web page provides a link for you to administer your server. Follow this link to the server administration applet, shown in Figure 47.3. Note that server administration takes place on port 9090, as a default.

FIGURE 47.3. The Java Web Server administration applet.

You can log in to this applet to administer your server. I won't cover server administration in any more detail than you'll need to install a servlet. The Java Web Server documentation explains all aspects of server administration.

To stop Java Web Server, just press Ctrl+C from within the DOS window in which it was started. On Windows NT, use the Services applet in the Control Panel to stop the Java Server service.

Using Servlets

Before I show you how to develop servlets, I'm going to whet your appetite by taking you on a tour of the servlets that come with Java Web Server.

Open your Web server to the default Web page ( Next, click on the link to Administer the Web Server. Here you'll find two Health Check servlets, as shown in Figure 47.4.

FIGURE 47.4. Links to Health Check Servlets.

Click on the link to the Link Checker servlet. This servlet provides a handy tool to check for broken links in your Web documents, as shown in Figure 47.5.

Go back to the previous page and click on the link to the Echo Servlet. This servlet echoes the Common Gateway Interface (CGI) parameters that are passed to it, as shown in Figure 47.6. You can use this servlet to debug your URLs.

FIGURE 47.5. The Link Checker Servlet.

FIGURE 47.6. The Echo Servlet.

Now use your browser to open the following URL:

Substitute your host name for The Protectedservlet illustrates the use of the access control features of Java Web Server. It prompts you with the login dialog, shown in Figure 47.7. If you fail to log in correctly three times, it displays the notice shown in Figure 47.8. If you do log in correctly (User name=jeeves and Password=jeeves), it displays the Web page shown in Figure 47.9.

FIGURE 47.7. The authorization dialog box.

FIGURE 47.8. Wrong password!

FIGURE 47.9. The protected Web page.

Writing Servlets

Now that you have a taste for servlets, I'll show you how they work and help you to develop a couple of your own.

Servlets are the server-side analog of applets. They are written to the Servlet API (covered in the next section) and are installed on a Web server. Besides Java Web Server, a number of Web servers support servlets and the Servlet API. The following list identifies some of these Web servers. A complete list can be obtained from

Servlets are located in the servlets directory of the Web server and can be invoked via the following URL:[?arguments]

The name of your Web server host (and port number) are substituted for, and the class name of your servlet is substituted for ServletName.class. The optional arguments are a standard URL-encoded query string.

Java Web Server can also be configured to associate servlets with other URLs or to be invoked as the result of processing a particular type of URL. Consult the Java Web Server documentation for information on how to do this. Most likely, the servlets that you'll develop will be similar to CGI programs in the services they provide. The advantages of servlets over CGI programs are that there is minimal server overhead in invoking them, they are provided with direct access to server resources, and they are written in Java.


The Servlet API is a Standard Extension API, meaning that it is not a part of the core Java Platform. See Chapter 51, "Java Platforms and Extensions," for a description of the Java Platform, the Core API, and the Standard Extension API. The Servlet API packages include the javax.servlet package and the javax.servlet.http package.

The javax.servlet Package

The javax.servlet package defines the following six interfaces and three classes:

The javax.servlet.http Package

The javax.servlet.http package is used to define HTTP-specific servlets. It defines the following interfaces and classes.

The TimeServlet Class

The TimeServlet class, shown in Listing 47.1, is a simple servlet that will ease you into servlet programming. Compile the servlet and move the TimeServlet.class file to Java Web Server's servlets directory. Don't worry about the deprecation warning. I'll explain it in the next section.

LISTING 47.1. THE TimeServlet CLASS.

import javax.servlet.*;

import java.util.*;


public class TimeServlet extends GenericServlet  {

 public String getServletInfo() {

  return "Time Servlet";


 public void service(ServletRequest request, ServletResponse response)

  throws ServletException, IOException {

  String date=new Date().toString();

  PrintStream outputStream = new PrintStream(response.getOutputStream());




Next, you must install the servlet on Java Web Server. To do this, open the URL Your server's administration applet is loaded and displays the login, shown in Figure 47.10. Log in as admin with the admin password.

FIGURE 47.10. The server administration applet.

After you log in, the administration main screen is displayed, as shown in Figure 47.11. Highlight the Web service and click on the Manage button to configure the Web service.

FIGURE 47.11. The server administration main screen.

The Web service administration screen is displayed, as shown in Figure 47.12. Click the Servlets button to add the TimeServlet.

FIGURE 47.12. The Web service administration applet.

The Servlets configuration screen is displayed, as shown in Figure 47.13. Click on Add in the selection list on the left of the screen to add a servlet to the list of servlets known to Java Web Server.

FIGURE 47.13. The Servlet administration applet.

An Add a New Servlet dialog appears, as shown in Figure 47.14. Enter TimeServlet for the servlet's name and TimeServlet.class for the servlet's class. Then click the Add button to add the servlet.

FIGURE 47.14. The Add a New Servlet dialog.

The screen is updated to display information about the servlet. Click the Load at Startup radio button to cause the servlet to be loaded automatically when the server starts. Then click the Save button to save the change. (See Figure 47.15.)

FIGURE 47.15. Completing the servlet's configuration.

You're finished configuring the servlet. Click the Load button to load the servlet, close the applet window, and then click the Log Out button to log out of the administration applet.

Now you're ready to use the TimeServlet servlet. Open the URL http://your.server. com:8080/servlet/TimeServlet.class to access the servlet. It displays the output shown in Figure 47.16.

If that seems like a lot of work just to get the time, hang in there. The next servlet will be more interesting and informative.

How TimeServlet Works

In order to use servlets, you must import the javax.servlet package, as shown in Listing 47.1. The TimeServlet class extends the GenericServlet class and overrides the getServletInfo() and service() methods. The getServletInfo() method returns a string that provides information about the servlet. The service() method implements the actual servlet request handling and response handling. It is invoked by the Web server when the URL of the servlet is requested. The server passes the ServletRequest and ServletResponse arguments to the servlet.

FIGURE 47.16. The TimeServlet's output display.

The TimeServlet is pretty simple and does not need any particular information contained in the ServletRequest object to perform its processing. It creates a new Date object, converts it to a String, and stores it using the date variable. It uses the getOutputStream() method of the ServletResponse class to create a ServletOutputStream object for sending response information back to the browser client. The ServletOutputStream object is filtered as a PrintStream.

NOTE: When you compile TimeServlet, you get a deprecation warning because you used PrintStream instead of its PrintWriter replacement.

Finally, you write the date string to the output stream to send it to the browser client.

The EchoRequest Servlet

The EchoRequest servlet, shown in Listing 47.2, shows how ServletRequest parameters are processed. Compile and copy the EchoRequest.class file to the servlets directory used by Java Web Server. Again, don't worry about the deprecation warning. Configure EchoRequest using the administration applet, as discussed for TimeServlet. Set its name to EchoRequest and its class name to EchoRequest.class. (See Figure 47.17.)

LISTING 47.2. THE EchoRequest SERVLET.

import javax.servlet.*;

import java.util.*;


public class EchoRequest extends GenericServlet  {

 public String getServletInfo() {

  return "Echo Request Servlet";


 public void service(ServletRequest request, ServletResponse response)

  throws ServletException, IOException {


  PrintStream outputStream = new PrintStream(response.getOutputStream());

  outputStream.print("Server: "+request.getServerName()+":");


  outputStream.print("Client: "+request.getRemoteHost()+" ");


outputStream.println("Protocol: "+request.getProtocol());

  Enumeration params = request.getParameterNames();

  if(params != null) {


    String param = (String) params.nextElement();

    String value = request.getParameter(param);

    outputStream.println(param+" = "+value);





FIGURE 47.17. Configuring the EchoRequest servlet.

Open the URL It displays the IP address and port number of the Java Web Server Web server, and the host name and address of the computer on which your browser resides. It also displays the version of the HTTP protocol being used. (See Figure 47.18.)

FIGURE 47.18. Using the EchoRequest servlet.

Now open the same URL with the ?n1=v1&n2=v2&n3=v3 query string appended. EchoRequest displays the name value pairs in the query string, as shown in Figure 47.19.

You can also use EchoRequest with forms. Copy the formtest.htm file, shown in Listing 47.3, to the public_html directory of your Web server. Open it with the URL The form shown in Figure 47.20 is displayed.

LISTING 47.3. THE formtest.htm FILE.



<TITLE>Using a form with EchoRequest</TITLE>



<FORM ACTION="servlet/EchoRequest.class">

Enter text: <INPUT NAME="textField" TYPE="TEXT" SIZE="30"><P>

Check this out: <INPUT NAME="checkbox" TYPE="CHECKBOX"><P>

Select me: <SELECT NAME="mySelection">

<OPTION>Number one

<OPTION>Number two

<OPTION>Number three






FIGURE 47.19. Using the EchoRequest servlet with a query string.

Enter a value for the text field, check or uncheck the text box, and make a selection from the selection list. Then click the Submit button. The EchoRequest servlet is invoked to process the form. It displays the output shown in Figure 47.21. Note that it correctly identifies the form values that you submitted.

FIGURE 47.20. Using the EchoRequest servlet with an HTML form.

FIGURE 47.21. EchoRequest displays the data you entered in the form.

How EchoRequest Works

As you would expect, the overall structure of EchoRequest is the same as TimeServlet. Both servlets extend GenericServlet and override the getServletInfo() and service() methods.

The service() method of EchoRequest begins by setting the content type of the response to the text/plain MIME type. We set the MIME type because we'll be generating more than one line of output and we don't want the browser client to mistake it for HTML.

Next, service() creates an output stream in the same manner as TimeServlet, using the getOutputStream() method of the ServletResponse interface. It then prints information about the server, client, and protocol that it obtains using the getServerName(), getServerPort(), getRemoteHost(), getRemoteAddr(), and getProtocol() methods of the ServletRequest interface.

The service() method invokes the getParameterNames() method of the ServletRequest interface to retrieve an enumeration of the parameter names that are passed in the query string of the HTTP request. It displays each parameter name along with its value. The parameter values are retrieved via the getParameter() method of the ServletRequest interface.


In this chapter, you installed Java Server and learned how it works. You learned about servlets and about the basics of the Servlet API. You then developed the TimeServlet and the EchoRequest servlet and learned how servlets can be used to process form data. In the next chapter, you'll learn more about the Servlet API and how to use servlets with other Web servers.

Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.