Java 1.2 Unleashed

Java 1.2 Unleashed
- 47 -
Sun's Java Web Server
- What Are the JavaServer Toolkit and Java Web Server?
- How Does Java Web Server Work?
- Installing Java Web Server
- Running Java Web Server
- Using Servlets
- Writing Servlets
- Summary
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:
- It listens on a port (or ports) for connection requests.
- It accepts connection requests.
- It creates threads to handle the requests.
- It hands the connections to the threads for processing.
- It manages the threads and connections.
Besides providing these basic server functions, the Java Server Toolkit makes it easier to integrate the following advanced capabilities into the servers you develop:
- Web-based remote administration
- Authentication and access controls
- Secure Sockets Layer (SSL)
- Servlets support
- HTTP 1.0 support
- Dynamic Web page generation
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:
- Java servlets can be used to replace CGI programs written in other languages.
- Web pages can be dynamically compiled based on server code that is embedded in
HTML files.
- User connections with the Web server can be tracked and managed as interactive
sessions.
- Secure Sockets Layer and X.509 digital certificates can be used to provide privacy,
integrity, and authentication services.
- Templates for the presentation of HTML content are separately managed by the server.
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 http://jserv.javasoft.com/products/java-server/webserver/index.html. 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:
C:\JavaWebServer1.0.3\bin>httpd
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 athome.jaworski.com. Figure 47.2 shows the server's default Web page, located at http://athome.jaworski.com:8080/.
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 (http://your.host.name.com:8080). 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:
http://your.host.com:8080/servlet/ProtectedServlet
Substitute your host name for your.host.name. 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 http://jserv.javasoft.com/products/java-server/servlets/environments.html.
- Apache 1.1.3
- Netscape FastTrack 2.0, Enterprise 2.0, Enterprise 3.0
- Microsoft IIS 2.0, IIS 3.0
- Weblogic Tengah
- Lotus Domino Go Webserver
- IBM Internet Connection Server
Servlets are located in the servlets directory of the Web server and can be invoked via the following URL:
http://your.host.com:port/servlet/ServletName.class[?arguments]
The name of your Web server host (and port number) are substituted for your.host.com:port, 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
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:
- javax.servlet interfaces
- Servlet--The Servlet interface must be implemented by all servlets. The init()
and destroy() methods are invoked by the server to start and stop a servlet. The
getServletConfig() and getServletInfo() methods are over-ridden to return information
about a servlet. The service() method is invoked by the server so that a servlet
can perform its service. It has two parameters--one of the ServletRequest interface
and one of the ServletResponse interface.
- ServletRequest--The ServletRequest interface encapsulates a client request for
service. It defines a number of methods for obtaining information about the server,
requester, and request. The getInputStream() method returns an object of the ServletInputStream
class that may be used to read request information sent by the client.
- ServletResponse--The ServletResponse interface is used by a servlet to respond
to a request by sending information back to the requester. The getOutputStream()
method returns an object of the ServletOutputStream class that is used to send response
information to the client. The getWriter() method returns a PrintWriter object that
is used for client communication. The setContentType() method sets the MIME type
of the response information. The setContentLength() method specifies the length of
the response in bytes. The getCharacterEncoding() method returns the MIME type associated
with the response.
- ServletConfig--The ServletConfig interface is used by the server to pass configuration
information to a servlet. Its methods are used by the servlet to retrieve this information.
- ServletContext--The ServletContext interface defines the environment in which
an applet is executed. It provides methods that are used by applets to access environment
information.
- SingleThreadModel--The SingleThreadModel interface is used to identify servlets
that must be thread-safe. If a servlet implements this interface, the Web server
will not concurrently execute the service() method of more than one instance of the
servlet.
- javax.servlet classes
- GenericServlet--The GenericServlet class is a convenience class that implements
the Servlet interface. You can subclass this class to define your own servlets.
- ServletInputStream--The ServletInputStream class is used to access request information
supplied by a Web client. An object of this class is returned by the getInputStream()
method of the ServletRequest interface.
- ServletOutputStream--The ServletOutputStream class is used to send response information to a Web client. An object of this class is returned by the getOutputStream() method of the ServletResponse interface.
The javax.servlet.http Package
The javax.servlet.http package is used to define HTTP-specific servlets. It defines the following interfaces and classes.
- javax.servlet.http interfaces
- HttpServletRequest--The HttpServletRequest interface extends the ServletRequest
interface and adds methods for accessing the details of an HTTP request.
- HttpServletResponse--The HttpServletResponse interface extends the ServletResponse
interface and adds constants and methods for returning HTTP-specific responses.
- HttpSession--This interface is implemented by servlets to enable them to support
browser-server sessions that span multiple HTTP request-response pairs. Since HTTP
is a stateless protocol, session state is maintained externally using client-side
cookies or URL rewriting. This interface provides methods for reading and writing
state values and managing sessions.
- HttpSessionBindingListener--This event listening interface is imple-mented by
classes whose objects are associated with HTTP sessions. The valueBound() method
is used to notify an object that it is bound to an HTTP session, and the valueUnbound()
method is used to notify an object that it is unbound from an HTTP session.
- HttpSessionContext--This interface is used to represent a collection of HttpSession
objects that are associated with session IDs. The getIds() method returns a list
of session IDs. The getSession() method returns the HttpSession object associated
with a particular session ID. Session IDs are implemented as String objects.
- javax.servlet.http classes
- Cookie--This class represents an HTTP cookie. Cookies are used to maintain session
state over multiple HTTP requests. They are named data values that are created on
the Web server and stored on individual browser clients. The Cookie class provides
the method for getting and setting cookie values and attributes.
- HttpServlet--The HttpServlet class extends the GenericServlet class to use the
HttpServletRequest and HttpServletResponse interfaces.
- HttpSessionBindingEvent--This class implements the event that is gen-erated when
an object is bound to or unbound from an HTTP session.
- HttpUtils--The HttpUtils class provides the parseQueryString() method for parsing a query string contained in an HTTP request.
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.*;
import java.io.*;
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());
outputStream.println(date);
}
}
Next, you must install the servlet on Java Web Server. To do this, open the URL http://your.server.com:9090/. 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 EchoRequest.java 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.*;
import java.io.*;
public class EchoRequest extends GenericServlet {
public String getServletInfo() {
return "Echo Request Servlet";
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintStream outputStream = new PrintStream(response.getOutputStream());
outputStream.print("Server: "+request.getServerName()+":");
outputStream.println(request.getServerPort());
outputStream.print("Client: "+request.getRemoteHost()+" ");
outputStream.println(request.getRemoteAddr());
outputStream.println("Protocol: "+request.getProtocol());
Enumeration params = request.getParameterNames();
if(params != null) {
while(params.hasMoreElements()){
String param = (String) params.nextElement();
String value = request.getParameter(param);
outputStream.println(param+" = "+value);
}
}
}
}
FIGURE 47.17. Configuring the EchoRequest servlet.
Open the URL http://your.server.com/servlet/EchoRequest.class. 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 http://your.server.com:8080/formtest.htm. The form shown in Figure 47.20 is displayed.
LISTING 47.3. THE formtest.htm FILE.
<HTML> <HEAD> <TITLE>Using a form with EchoRequest</TITLE> </HEAD> <BODY> <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 </SELECT><P> <INPUT NAME="Submit" TYPE="SUBMIT"> </FORM> </BODY> </HTML>
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.
Summary
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.
© Copyright, Macmillan Computer Publishing. All rights reserved.