| By Chad Darby | Article Rating: |
|
| January 1, 1998 12:00 AM EST | Reads: |
10,531 |
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.
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:
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.
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.
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.
I. Regional Settings
Some PowerBuilder features, such as DataWindow query mode and the Date() function, use the [shortdate] format defined in the regional settings control panel (see Figure 1).
The first step you should take toward Y2K compliance is to adopt a standard [shortdate] format that includes a four-digit year. You can't simply circumvent the control panel by explicitly specifying formats on all dates because PowerBuilder uses [shortdate] in date formats that you can't override. Also, hard-coding mm/dd or dd/mm may cause problems for users from other countries, where different standards for the relative order of month and day may apply. Even if you only deploy locally, users may still have changed their control panel settings. If you use [date] as the format for your edit masks, you ensure that your interface and the operating system settings align properly ([date] resolves to [shortdate]). By checking the registry, you can verify in code that the [shortdate] format includes a four-digit year. See Listing 1 for an example of how to do so.
Initial values that you set in controls or columns are subject to the [shortdate] settings, as are string/date conversions without explicit formats. When you use a string to assign a date value without providing an explicit format, PowerBuilder uses [shortdate] to interpret the date. PowerBuilder also assigns default formats when you place data fields on a window or DataWindow. Columns and computed fields that default to [general] ultimately resolve to [shortdate], but date edit masks start with mm/dd/yy and must be manually set to show century information. Using the PowerBuilder repository to store default column formats in the database is a good practice, but avoid relying entirely on the repository to set your column formats. See Listing 2 for examples of the impact [shortdate] can have on your code. You can remove some of the risk of this dependence on a system setting by using graphical calendars for user data entry. Alternatively, in PowerBuilder 6.0, if you check the Use Format box on the Edit tab of a column's property sheet, you can use a format for display and an edit mask for editing (see Figures 2 and 3).
II. Ambiguous Century
The most publicized category of Y2K risk comprises dates without clearly indicated century information. In PowerBuilder, since the date and datetime datatypes always carry century information, century problems arise from date/string conversions that lack adequate formatting or validation or when a date's component parts (year, month, day) are manipulated or stored as strings or integers. Remember that implicit or explicit string conversion takes place whenever your application gets a date from a file or a user interface.
Code that assumes a given century is extremely common. The most obvious example pastes a century in front of a two-digit year, as in Listing 3. You'll often find examples like this one at the tail end of extensive string manipulation of a date. Ironically, a desire to avoid century problems often motivates such code.
User interfaces that allow only two-digit year entries can discard century information. For example, if you retrieve the date 1945-12-16 into a column with a "mm/dd/yy" edit mask, PowerBuilder will initially retain the underlying date value. When a user edits the column, perhaps changing the year to "46," the column display will change by one year ("12/16/46") but the underlying value will follow the windowing rules and change to 2046-12-16. You could lose more than just century information by careless use of edit masks - any hidden part of the date will be set to a default value if the visible part is modified. See Listing 4 for an example of this risk.
Century ambiguity cuts in both directions. Reports that display two-digit years may not be clear to users, even if your application has century information in the underlying - but invisible - date values. Similarly, if you display date validation messages that don't include century information, users may find the messages confusing or meaningless. See Listing 5 for an example. Another output issue involves sorting. Without century information, dates in string format may not sort correctly (0 will sort before 9). Unless date strings are formatted YYYY-MM-DD, an alphanumeric sort will not order them chronologically.
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.
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.
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();
while (e.hasMoreElements())
{ " + name + ": " + value;
String name, value;
name = (String) e.nextElement();
value = request.getParameter(name);
replyPage += "
}
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.
Published January 1, 1998 Reads 10,531
Copyright © 1998 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Chad Darby
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.
- Kindle 2 vs Nook
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- Confessions of a Ulitzer Addict
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- It's the Java vs. C++ Shootout Revisited!
- Cloud Computing Can Revitalize Your Career as Software Developer
- IBM Could "Reinvent" Java: Mills
- Oracle & Cloud Computing: Exclusive Q&A with SVP Richard Sarwal
- A Brief History of Cloud Computing
- Kindle 2 vs Nook
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- Why IBM’s Server Chief Got Busted
- Is Cloud Computing Like Teenage Sex?
- Industry Experts Discuss the State of Cloud Computing
- Performance Tuning Essentials for Java
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing Expo: Exclusive Q&A with Yahoo! SVP Cloud Computing
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- The i-Technology Right Stuff
- JavaServer Faces (JSF) vs Struts
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate
- What's New in Eclipse?
- Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
- i-Technology Predictions for 2007: Where's It All Headed?



































