HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Introduction
The rapid acceptance of Java for client and server applications has created an immediate need to move existing CGI scripts to Java servlets. Java servlets are server-side components that can extend the functionality of a Java-enabled web server. Currently, there are a number of enterprise web applications that provide server-side functionality with CGI scripts. Java servlets provide a number of enhancements to the current CGI architecture.

In this article, you will learn what servlets are, how you can integrate them into your web application and what the benefits of using servlets are. An overview of the Java servlet API is given along with servlet examples for accessing CGI environment variables and processing HTML form data.

Java Servlet Primer
What Is A Servlet?
A Java servlet is a server-side component that is platform and protocol independent. Servlets can be used to extend the functionality of a Java-enabled web server. You can think of a servlet as a faceless applet. Servlets are loaded and invoked by the web server in much the same way that applets are loaded and invoked by web browsers.

Platform Independence
You can use a servlet to perform typical server-side processing. The servlet can communicate with the client computer and it can also communicate with other remote, networked computers. In an n-tiered environment, your middleware can be implemented as a servlet. A three-tier architecture is illustrated in figure 1.

Figure 1
Figure 1:

The following examples show how servlets can be used for data retrieval and system monitoring.

Apartment Locator Applet
The Apartment Locator applet can be used to search for apartments that match a user's criteria. The user will be able to request the city, number of bedrooms, price range, etc. The applet can send this information to the servlet for processing. The servlet, functioning as the middleware, will make the database query. The servlet can then return the query results to the applet.

Network Healthcare Monitor
An intelligent agent can be implemented as a servlet to monitor the health of your computer network. The servlets can poll host machines on your network at given intervals and ensure that the basic services are operating. The results can be stored in a database or displayed in a real-time graphical applet. In the event of an emergency, the servlet could send e-mail to the system administrator.

These are just some examples of using servlets. Practically any server-side process can be implemented as a servlet.

What Are The Benefits of Using Servlets?
Platform Independence
You can develop a complex server-side application without restricting it to a particular hardware platform. Client-side Java applets introduced the notion of platform independence for the client. Java servlets take this idea to another level: the server. Today your application server can reside on a Windows NT platform and then you can later move it to the UNIX platform. This migration can take place without the headaches associated with porting code and without the need to recompile your Java servlets.

Network Programming
Your Java servlets have full access to Java's networking features. The servlets can connect with other networked computers using sockets or Remote Method Invocation (RMI). Also, the servlet can easily connect to a relational database using the Java Database Connection (JDBC). By using the networking features of Java, servlets can be used to easily develop middleware.

Reuse and Modularity
One shortfall of server-side programming in scripting languages such as Perl and VBScript is that of reuse. If you have to create another server-side module based on existing code then the only reuse you have with scripting languages is "cut-and-paste" reuse.

Since servlets are written in Java, you gain all the object-oriented features of Java such as reuse. You can create an object framework of common servlets and reuse them in future applications. For example, you can create a simple servlet for processing of HTML form data. Later, another developer can use this servlet as is or extend it to add custom functionality.

Supporting the idea of modularity, servlets can communicate with other servlets on the web server. This mechanism, known as servlet chaining, allows the output of one servlet to be passed as input to another servlet. As an example, a database query servlet can retrieve sales data and pass this data to a charting servlet. The charting servlet simply prepares a graphical representation of the data and returns it to the client.

Performance
The problem with traditional CGI applications is performance. Each time a CGI application is requested by the client, a new process is spawned. This is expensive when the Perl interpreter is loaded and executed for each client request. This could easily lead to performance problems at popular web sites that handle requests from multiple users.

One solution to this problem is addressed in the Java Servlet Architecture. The first time a Java servlet is requested, it is loaded into the web server's memory space. Subsequent client requests for the servlet result in calls to the servlet instance in memory. This process is more efficient than the traditional CGI implementation. As a result, the performance of server-side applications increases.

Web Servers Supporting Java Servlets
Java servlets are available with Java-enabled web servers. The first web server supporting servlets was Sun Microsystem's Java Web Server. A number of companies have signed up and have released or are in the process of releasing Java-enabled servers. At the time of this writing, the following web servers supported servlets or had made announcements:

  • Netscape FastTrack 2.0, Enterprise 2.0, Enterprise 3.0
  • Microsoft IIS 2.0, 3.0
  • O'Reilly WebSite Professional V2 Server
  • Lotus Domino Go Webserver
  • Apache 1.1.3
  • Novell IntraNetWare
  • IBM Internet Connection Server
If your web server does not support servlets then there are third-party server add-ons. Live Software offers a product called JRun. JRun is a set of classes and native code that can extend your web server to support servlets. This product can be used to add Java servlet functionality to Microsoft's IIS and Netscape's web servers. Visit Live Software's web site for more details: www.livesoftware.com. It is also a good idea to check with your web server vendor for servlet support and release dates.

Sun's Java Web Server At A Glance
You can start developing Java servlets today by downloading the Java Web Server from Sun Microsystems. The current platforms supported are Sun Solaris 2.x and Windows 95/NT. Also, the Java Development Kit (JDK) 1.1.2 or greater is required.

At the time of this writing, the final release of Java Web Server version 1.0.3 was available at Sun Microsystem's web site: http://jserv.javasoft.com

The download contains simple instructions for installing and running the web Server. You can confirm that it is properly installed and running by loading the default web page at http://localhost:8080/. By default, the web server is listening on port 8080 as opposed to port 80. The web server's home page has a number of useful links to developer and administrator documentation.

The Java Web Server has an administration tool that is written as a Java applet. You can administer the web server by opening http://localhost:9090. The default user name is admin and the default password is admin. Once logged in, you will see the Administrator applet as shown in figure 2.

Figure 2
Figure 2:

The Administrator applet can be used to perform a number of operations such as add servlets, set up security parameters and set up servlet aliases. There are numerous other operations available and they are fully documented in the Administrator documentation. You will use the Administrator applet frequently during servlet development.

Servlet API Overview
The Java Servlet API is composed of two main packages: javax.servlet and javax.servlet.http.

The javax.servlet package has a collection of classes and interfaces for writing servlets that are protocol independent. The servlet can communicate with the client using a custom protocol. Tables 1 and 2 show the most useful classes. A complete list of classes and interfaces can be found in the online documentation available with the Java Web Server.

Table 1

Table 2

You can use the javax.servlet.http package to communicate with HTTP specific client requests.

Basic Servlet Code Example
The time has come to view actual Java code for a servlet. Basically, all you have to do is extend from a servlet class. You have a choice here of extending from the abstract classes' GenericServlet or HttpServlet. You can use the GenericServlet class for basic server-side processing. As a web developer, migrating CGI scripts to Java, you will most likely use the HttpServlet class. The HttpServlet class provides protocol support for HTTP 1.0. Listing 1 is a code skeleton for a basic HttpServlet.

First, the packages, javax.servlet and javax.servlet.http, are imported. Next, the class TestWebServlet is declared as public and extends from HttpServlet. The main entry point for your servlet is through the service() method. You will do the majority of your processing in this method. When your servlet is called by a client program, the service() method is invoked. The two parameters, HttpServletRequest and HttpServletResponse, contain client request and response information. These parameters will be used for communicating with the client.

The first parameter, an HttpServletRequest object, contains information specific to this client's request. In traditional CGI programming, this information could be read from the standard input stream (stdin). However, using the Java Servlet API you will access this information using an HttpServletRequest object. You can query this object to find out the client's host machine name and IP address. You also have the ability to find out the HTTP method used by the client to request information (i.e., GET, HEAD, POST, PUT). The most valuable method available in this HttpServletRequest object is the getParameter() method. This method allows you to provide the parameter name, the name of a form field for instance, and then the parameter value is returned. Here is an example of calling the getParameter method:

String userName = request.getParameter("Name");

The second parameter, an HttpServlet- Response object, is your vehicle for passing data back to the client. Basically, this works similarly to traditional CGI programming. However, instead of writing your information to the standard output stream (stdout) you will use the output stream provided by the client. To get the client output stream, simply call the getOutputStream() method on the HttpServletResponse object. With this output stream, you can construct a PrintStream for sending back your response. Here is an example of constructing a PrintStream:

PrintWriter out = new PrintWriter
(response.getOutputStream());

Now you have seen the basic framework for an HttpServlet. You are probably very eager to write, compile and run your first servlet. Well, you are in luck because now we will discuss the steps of servlet development.

Servelt Development Process
The basic steps for developing a servlet are outlined below:

  1. Write the code.
  2. Compile the code.
  3. Add servlet to Web Server.
  4. Test the servlet.
So, let's go through this development process with a test servlet which will send a reply page to the client. The page is a simple thank you note with the client IP address listed:

Thanks for calling the servlet from 127.0.0.1

Step 1: Write the code
Listing 2, TestWebServlet.java, provides the complete code for our test servlet.

Before you compile the program, take a look at the Java code. Notice that the servlet extends from HttpServlet. As stated earlier, the service() method is the servlet entry point so the bulk of the processing is accomplished here. The client's IP address is provided by calling the getRemoteAddr() method on the HttpServletRequest object. Additional HttpServletRequest methods will be presented in a later section. As in traditional CGI programming, the reply page is created using strings with embedded HTML tags. Next, the content-type is set for the response header using the HttpServletResponse object. Finally, an output stream is created and the page is transmitted to the user. It is important to note that the output stream from the HttpServ-letResponse object is used instead of the standard output stream.

Step 2: Compile the code
When compiling the code for TestWebServlet.java, you must ensure two things:

  • The Java servlet classes are in your classpath.
  • The .class file generated is placed in the server_root/servlets subdirectory.
For the classpath, the Java servlet classes are located in server_root/lib/classes.jar. server_root is the root directory where you installed the Java Web Server. To make life easy, you should modify your CLASSPATH environment variable.

By compiling the source code, a TestWebServlet.class file is generated. This file, TestWebServlet.class, must be copied to the servlet subdirectory located at server_root/servlets. If you don't want to manually copy the file after each compile, you can use the -d option on the javac command to automatically place the .class file in the specified directory. Here is an example of the command:

$ javac -d server_root/servlets
TestWebServlet.java

Step 3: Add Servlet to Web Server
Now, in order for the web server to recognize your new servlet, you have to add it to the web server. This is basically a registration process for the servlet.

Assuming that you are still using Sun's Java Web Server, you can follow these steps:

  • If the Java Web Server is not running, start it now. Refer to the steps provided in the Installation section presented earlier in the article.
  • Log on to the administrator applet by opening the following URL:
http://localhost:9090
user id = admin, password = admin (default id and password)
If successful, then the main administrator applet is loaded.
  • Once the main administrator applet is loaded, highlight the "Web Service" and click the "Manage" button. If all works well, you should now see the "Web Service" window.
  • Now click on the "Servlets" button and select "Add" from the tree in the left pane.
  • In the center pane, you can enter the following information:
Servlet Name = TestMe
The Servlet Name field is a logical handle for the Web server. This name does not depend on the name of the servlet class file.

Servlet Class = TestWebServlet
The Servlet Class field is the true name of the servlet class. Notice that you do not provide the .class extension, only the class name.

Once entered, click the "Add" button in the bottom of the center pane. Close the window.

Step 4: Test the Servlet
You can check if your servlet was properly added to the web server by invoking the servlet. Use the following URL:

http://localhost:8080/servlet/TestMe

If all is well, the servlet will give you a thank you page with your IP address similar to the message shown in figure 3.

Figure 3
Figure 3:

Congratulations! You have successfully developed a Java servlet. Now you can follow the previous steps for developing your own custom servlets.

Servlet Life Cycle
By now, you are probably curious about the servlet's life cycle. A servlet has three life cycle methods: init(), service() and destroy(). These methods are called directly by the web server. The life cycle methods are described in detail in Table 3.

Table 3

Recall that in an earlier section we discussed the benefits of Java servlets. One of those benefits is performance, because the servlet process is spawned only once during its lifetime. This is in contrast to traditional CGI scripts that spawn a new process each time the CGI script is invoked. As you can see from Table 3, the init() method is called only once to spawn the new process. Subsequent calls to the servlet results in only the service() method being called.

Make the Migration!
You now understand the basics of Java servlet development. In this section, you will apply this knowledge to migrate your CGI scripts to Java servlets. Example servlets will be presented for accessing environment variables and echoing form data.

Accessing Environment Variables
In your current CGI applications, you might have a need to access the CGI environment variables to process the client's request. As you will see, the environment variables provide very useful information about the client such as the browser type, IP address and host name.

The Java Servlet API provides support for accessing environment variables. You can use the methods in the HttpServletRequest interface to retrieve this information. The HttpServletRequest interface inherits the majority of its methods from ServletRequest.

Table 4 provides a list of CGI variables along with the corresponding methods in HttpServletRequest.

Table 4

Echo Environment Variables Servlet
Let's create a simple servlet that will echo the environment variables using the HttpServletRequest methods.

You will use the same servlet development process presented earlier. Recall this process is: write the code, compile the servlet, add the servlet and finally test it. Let's follow this process step-by-step.

Step 1: Write the Code
Listing 3, EchoEnvironmentServlet.java, provides the complete source code for the servlet.

Notice that as before, a bulk of the work is accomplished in the service() method. The basic header of the web page is created and then the environment variables are accessed by calling the methods available in the HttpServletRequest class. These are the same methods listed in Table 4. Once the page is created, it is passed back to the client. As before, you can send data back to the client by writing to the client's output stream.

Also, make note of the getServletInfo() method. This method is available in the HttpServlet class and we're simply overriding it. This is a developer-friendly method that can provide information on the servlet such as the author's name, date, revision and a shameless plug for the corporate web site.

Step 2: Compile the servlet
Make sure you have the classpath set to server_root/lib/classes.jar. To compile, issue the following command:

$ javac -d server_root/servlets
EchoEnvironmentServlet.java

This will create the class file EchoEnvironmentServlet.class and automatically store it in the server_root/servlets sub-directory.

Step 3: Add the servlet
Remember, you have to add the servlet to the web server.

  • Log in to the Web server. For details on logging in, refer to the section where you developed TestWebServlet.
  • Double click the "Web Service" to manage it and then click the "Servlets" button.
  • Now click the "Add" button and give the following information:
Servlet Name = EchoEnviro
Servlet Class = EchoEnvironmentServlet

Once entered, click the "Add" button in the bottom of the center pane. Close the window.

Step 4: Test the Servlet
You can check if your servlet was properly added to the web server by invoking the servlet. To invoke your environment variables servlet, use the following URL:

http://localhost:8080/servlet/EchoEnviro

Your servlet should return a web page that lists the different environment variables. Also, as a bonus, this servlet displays the MIME-type header information.

As you can see, accessing environment variables in a Java servlet is very straight-forward. So now you can easily write a Java servlet that can identify the web browser being used by the client.

Reading The Form Data
With the knowledge you've gained so far about Java servlets, you now have the skills to process HTML form data. Forms can be used to gather user information for an order request, class registration or magazine subscription request. In this section, you will develop an HTML form and also a Java servlet to process a magazine subscription.

Step 1: Develop the HTML Form
First, we have to develop the HTML form. This form is your traditional magazine subscription form. Figure 4 is a screen shot of the form.

Listing 4, MagazineForm.html provides the complete HTML code for the form. CAUTION: Form POSTing Buglet

I was migrating an enterprise CGI application to Java servlets when I ran into a bug while using the POST method to pass form data. This bug appears when using the Java Web Server 1.0.3 on the Windows 95 platform. If your form tries to POST data then you will get the following error:

A network error occurred while receiving data.
Network Error: Connection reset by peer.

Since my project deadline was fast approaching, I used a simple work-around. Instead of using the POST method, I used the GET method in the HTML form.

Step 2: Develop the Magazine Form Servlet
The magazine form servlet (see Figure 4) will read information from the client's submission. Once the form fields are accessed, a confirmation HTML page is returned to the user.

Figure 4
Figure 4:

1. Write the servlet code
Listing 5, EchoMagazineServlet.java, provides the complete code for the Java servlet.

Notice that in this example we are overriding the life cycle method, init(). In this method we call the constructor of the superclass. However, the item of interest here is the initialization of the integer variable, counter. The counter is used to display the number of subscription forms submitted. The counter variable illustrates the fact that only one instance of the servlet is created. During repeated calls to the service() method, the counter is incremented.

As usual, we process the client request in the service() method. The counter variable is incremented in the first couple of lines in the service() method. Then, the basic HTML header tags are added to the replyPage string. A line of text is added to display the subscriber count by accessing the counter variable. Next, the form data is accessed by calling the getParameter() method with the name of the HTML form field. The servlet information is added at the bottom of the page by calling the getServletInfo() method. Finally, the servlet responds to the client by returning the constructed HTML page. 2. Compile the servlet code

$ javac -d server_root/servlets
EchoMagazineServlet.java

3. Add the servlet to the web server
Refer to the "add servlet" steps presented earlier in this article. Use the following information for Servlet Name and Servlet Class fields.

Servlet Name = EchoMagazineForm
Servlet Class = EchoMagazineServlet

4. Test the servlet
Using your Web browser, open the html page, MagazineForm.html. Enter some sample user data and press the "Subscribe" button. A confirmation message should be returned to the web browser.

This example uses a basic, practical approach for accessing form data. There are a number of useful methods available in the HttpServletRequest class. If you are building a dynamic and robust servlet for reading forms then you can call the getParameterNames() routine to get a list of parameter names. The list of parameter names corresponds to the names of the HTML form input fields. The parameter list is actually returned as an Enumeration object.

The following is a simple code fragment that uses the getParameterNames() method:

Enumeration e = request.getParameterNames();
String name, value;

while (e.hasMoreElements()) {
name = (String) e.nextElement();
value = request.getParameter(name);


replyPage += "

" + name + ": " + value;
}

Also, if your servlet needs to read files on the web server then you can use the HttpServletRequest.getRealPath() method. This method is useful because you can provide the relative web file path and the absolute file path is returned. Once you have the absolute path then you can easily create a FileInputStream or FileOutputStream.

If you want to redirect the web browser to a new web page then you can use the HttpServletResponse.sendRedirect() method and provide a URL string. Also, you can gracefully recover from exceptions by sending an error page. In this situation, call the HttpServletResponse.sendError() and provide the error code and error string.

As you can see, the Servlet API provides a great deal of support for communicating with the web client.

Conclusion
Java servlets give you the capability to develop complex server-side applications. Servlets leverage Java's object-oriented features to build reusable and modular components. You can easily create servlets to replace CGI applications, access databases and communicate with remote computers.

The new beta release of the Servlet API provides support for cookies and session management. The API also features HTML page compilation with embedded Java code and HTML templates.

You can use the information in this article to migrate your existing CGI applications to Java servlets. If you want a server-side application that is reusable, maintainable and efficient then you should make the migration!

In the next article, you will learn how to build a data-aware servlet using JDBC.

References
Article Listings:
http://www.j-nine.com/pubs/jdj
Java Servlet API: http://jserv.javasoft.com
Live Software, Jrun 2.0: http://www.livesoftware.com
This article is based on Java Web Server 1.0.3 final. Some details may have changed by the time you read this.

About the Author
Chád (shod) Darby is a Java consultant for J9 Consulting, www.j-nine.com. He specializes in developing server-side Java applications and database applications. He also provides Java training for Learning Tree International. Chád can be reached at: [email protected]

	

Listing 1.
 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.*; 
public class TestWebServlet extends HttpServlet 
{ 

    public void service(HttpServletRequest request,  
HttpServletResponse response) 
        throws ServletException, IOException 
    { 
//  get input from the client using the HttpServletRequest parameter 

 //  process the data 

 //  return output to the client using the HttpServletResponse parameter 
    } 
     
} 

Listing 2.
 
import javax.servlet.*; 
import javax.servlet.http.*; 
import java.io.*; 

//  File:  TestWebServlet.java 
//  Listing 1 
// 
/** 
 * 
 *  This servlet responds with a simple thank-you note displaying <p> 
 *  the client's IP address. 
 * 
 *  @author Chad (shod) Darby,  [email protected] 
 *  @version 1.369, 13 Nov 97 
 * 
 */ 
public class TestWebServlet extends HttpServlet 
{ 
    protected void service(HttpServletRequest request,  
HttpServletResponse response) 
        throws ServletException, IOException 
    { 
        String clientIPAddress = request.getRemoteAddr(); 
        String replyPage = null; 

        //  Build HTML page 
        // 
        replyPage = "<HTML><HEAD><TITLE>Test Web Servlet</TITLE></HEAD>"; 
        replyPage += "<BODY>"; 
        replyPage += "<P>Thanks for calling the servlet from " + clientIPAddress; 
        replyPage += "</BODY></HTML>"; 

        //  Set the content type of response 
        // 
        response.setContentType("text/html"); 

        //  Get the output stream to the client response and send the page. 
        //  Note:  The PrintWriter class is a new addition to Java 1.1 
        // 
        PrintWriter out = new  
PrintWriter(response.getOutputStream()); 
        out.println(replyPage); 
        out.flush(); 
        out.close(); 
    } 
} 

Listing 3.
 
import javax.servlet.*; 
import javax.servlet.http.*; 

import java.io.*; 
import java.util.*; 

//  File:  EchoEnvironmentServlet.java 
//  Listing 2 
// 
/** 
 *  This servlet displays the CGI environment variables in a web page. 
 * 
 *  @author Chad (shod) Darby,  [email protected] 
 *  @version 3.41, 2 Nov 1997 
 * 
 */ 
public class EchoEnvironmentServlet extends HttpServlet 
{ 

    public void service(HttpServletRequest request,  
HttpServletResponse response) 
     throws IOException 
    { 
        String replyPage = null; 

        // Build the header for HTML page 
        // 
        replyPage = "<HTML><HEAD><TITLE>Echo Environment  
Variables</TITLE></HEAD>"; 

        replyPage += "<BODY>"; 

        // Echo the environment variables 
        // 
        replyPage += "<H2>  Environment Variables </H2>"; 

        replyPage += "<p><b> Server Name: </b>" +  
request.getServerName(); 
        replyPage += "<p><b> Server Port: </b>" +  
request.getServerPort(); 
        replyPage += "<p><b> Server Protocol: </b>" +  
request.getProtocol(); 
        replyPage += "<p><b> Servlet Name: </b>" +  
request.getServletPath(); 

        replyPage += "<p><b> Method: </b>" + request.getMethod(); 
        replyPage += "<p><b> Path Info: </b>" +  
request.getPathInfo(); 
        replyPage += "<p><b> Path Translated: </b>" +  
request.getPathTranslated(); 
        replyPage += "<p><b> Query String: </b>" +  
request.getQueryString(); 
        replyPage += "<p><b> Request URI: </b>" +  
request.getRequestURI(); 

        replyPage += "<p><b> Remote Host: </b>" + request.getRemoteHost(); 
        replyPage += "<p><b> Remote Addr: </b>" + request.getRemoteAddr(); 
        replyPage += "<p><b> Remote User: </b>" +  
request.getRemoteUser(); 
        replyPage += "<p><b> Authorization Type: </b>" + request.getAuthType(); 

        replyPage += "<p><b> Content Type: </b>" +  
request.getContentType(); 
        replyPage += "<p><b> Content Length: </b>" +  
request.getContentLength(); 

        replyPage += "<hr>"; 

        // Just for kicks, let's loop thru and get the header info using an enumeration 
        // 
        replyPage += "<H2>  Request Header Information </H2>"; 
        Enumeration e = request.getHeaderNames(); 
        String name; 

        while (e.hasMoreElements()) 
        { 
          name = (String) e.nextElement(); 
          replyPage += "<p><b>" + name + ": </b>" +  
request.getHeader(name); 
        } 
        replyPage += "<hr>"; 

        //  Build bottom of HTML page 
        // 
        replyPage += "</BODY> </HTML>"; 

        //  Set the content-type for the response header 
        //  note: no need for extra carriage returns! 
        // 
        response.setContentType("text/html"); 

        //  finally, send this formatted HTML page back to the client 
        // 
        PrintStream out = new PrintStream(response.getOutputStream()); 
        out.println(replyPage); 
        out.close(); 
  } 

  public String getServletInfo() 
  { 
    return "Echo Form Servlet,  Chad (shod) Darby, 2 Nov 1997, www.j-nine.com"; 
  } 
} 

Listing 4.
 
<!-- FILE:  MagazineForm.html --> 
<!-- LISTING 3                --> 

<HTML> 
<HEAD> 
   <TITLE>Magazine Subscriptions</TITLE> 
</HEAD> 
<BODY> 

<CENTER> 
<H1> 
Magazine Subscription Form</H1></CENTER> 

<HR><FORM method="GET" action="http://127.0.0.1:8080/servlet/EchoMagazineForm"> 
<H3> 
Name and Address</H3> 

<TABLE> 
<TR> 
<TD>Name</TD> 

<TD><INPUT type=text size=20 name="Name"></TD> 
</TR> 

<TR> 
<TD>Address</TD> 

<TD><INPUT type=text size=20 name="Address"></TD> 
</TR> 

<TR> 
<TD>City</TD> 

<TD><INPUT type=text size=20 name="City"></TD> 
</TR> 

<TR> 
<TD>State</TD> 

<TD><INPUT type=text size=20 name="State"></TD> 
</TR> 

<TR> 
<TD>Zip Code</TD> 

<TD><INPUT type=text size=20 name="Zip Code"></TD> 
</TR> 
</TABLE> 

<H3> 
Payment Method</H3> 

<OL> 
<LI> 
Bill Me In Full  <INPUT type="radio" name="Payment Method" value="Bill Me In Full"></LI> 

<LI>  
Bill Me In 3 Installments  <INPUT type="radio" name="Payment Method" value="Bill Me In 3 Installments"></LI> 

<LI>  
Payment Enclosed  <INPUT type="radio" name="Payment Method" checked value="Payment Enclosed"></LI> 
</OL> 

<TABLE> 
<TR> 
<TD></TD> 

<TD><INPUT type=submit value="Subscribe"></TD> 

<TD><INPUT type=reset value="Reset"></TD> 
</TR> 
</TABLE> 
</FORM> 
<HR> 
</BODY> 
</HTML> 

Listing 5.
 
import javax.servlet.*; 
import javax.servlet.http.*; 

import java.io.*; 
import java.util.*; 

//  File:  EchoMagazineServlet.java 
//  Listing 4 
// 
/** 
 *  This servlet displays the fields of a magazine subscription form in a web page. 
 * 
 * 
 */ 
public class EchoMagazineServlet extends HttpServlet 
{ 
  private int counter; 

  public void init(ServletConfig config) throws ServletException 
  { 
    super.init(config); 
    counter = 0; 
  } 

  public void service(HttpServletRequest request,  
HttpServletResponse response) 
 throws ServletException, IOException 
  { 
    String replyPage = null; 

    // our servlet is being called, increment the counter 
    // 
    counter++; 

    //  Build HTML page’s header information 
    // 
    replyPage = "<HTML><HEAD><TITLE>Subscription Confirmation"; 
    replyPage += "</TITLE></HEAD>"; 

    replyPage += "<BODY>"; 
    replyPage += "<H1>Subscription Confirmation</H1>"; 
    replyPage += "<HR>"; 

    //  Thank user for subscribing and show value of "counter" 
    // 
    replyPage += "Thank you for subscribing."; 
    replyPage += "You are subscriber <b># " + counter + "</b>"; 
    replyPage += "<P>We will send the magazine to the mailing address below."; 

    //  Print out the values for form variables. 
    //  Notice we use HTML formatting to "spiff-up" the data 
    // 
    replyPage += "<UL>"; 
    replyPage += "<LI> <B>Name:</B>  " + request.getParameter("Name"); 
    replyPage += "<LI> <B>Address:</B>  " + request.getParameter("Address"); 
    replyPage += "<LI> <B>City:</B>  " + request.getParameter("City"); 
    replyPage += "<LI> <B>State:</B>  " + request.getParameter("State"); 
    replyPage += "<LI> <B>Zip Code:</B>  " + request.getParameter("Zip Code"); 
    replyPage += "<LI> <B>Payment Method:</B> " +  
request.getParameter("Payment Method"); 
    replyPage += "</UL>"; 

    replyPage += "<HR>"; 
         
    replyPage += "<P>" + this.getServletInfo(); 
     
    //  Build bottom of HTML page 
    // 
    replyPage += "</BODY></HTML>"; 

    //  Set the content-type for the response header 
    // 
    response.setContentType("text/html"); 

    //  finally, send this formatted HTML page back to the client 
    // 
    PrintWriter out = new PrintWriter(response.getOutputStream()); 
    out.println(replyPage); 
    out.close(); 
  } 

  public String getServletInfo() 
  { 
    return "Echo Magazine Form Servlet v5.49, 2 Nov 1997"; 
  } 
}


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.