Anyone developing business applications in Java uses the Servlets API. Even though Sun introduced servlets just over a year ago, servlets are already a pervasive technology. Keep an eye on the URLs at the top of your browser for the next few weeks. A URL containing a qualifier with suffix .nsf indicates that a Lotus Domino application is driving the content. Directory name cgi-bin signifies that the application uses a legacy language with Common Gateway Interface (CGI). If loading Java... appears at the bottom of your browsers screen, it doesnt really matter, because youre probably moving to another site because you dont want to wait for the Java applet to download. Qualifier servlet is a sure sign that host-based Java servlet technology is driving the application.
Host-based Apps Rule
Java applets have fallen out of favor for Internet business applications. Applets were all the rage because they delivered client-side business applications over the Web. Web designers began using applets because they presented a graphical interface far superior to HTML, but they soon discovered that applets were fat clients because the code required to present that superior interface leaned toward obesity. Java servlets, on the other hand, are host- based. Servlets keep business logic on the server, and because the user interface for servlets is HTML, download speeds are not an issue. Some client-side logic may be required, but, more often than not, you can implement that client-side processing via a scripting language such as JavaScript or VBscript.
Dynamic generation of HTML with Java servlets is the same strategy CGI programmers have used for several years. CGI allows you to associate a URL request with a host program that can be implemented using your language of choice. However, on most platforms, each time a URL invokes a CGI program, that program is restarted, incurring normal expenses of security checks, memory allocation, and file opens. Once the program completes the request by returning an HTML response containing dynamically constructed information, that program instance is purged. Each subsequent invocation of the CGI program imposes a program initialization penalty on the server. Java servlets, in contrast, are not purged; the servlet instance remains available to the Web server for invocation by multiple clients.
Now, I must be honest. Earlier, I said on most platforms when noting the superiority of servlets over CGI, but the AS/400 is not an ordinary platform. Using a combination of activation groups and the Persistent CGI feature new with V4R3, CGI application performance on the AS/400 is far superior to CGI on most platforms. Application portability is the issue. With considerations such as security, caching, and clustering, Web server configuration is complicated. Consequently, many Web sites have multiple platforms that support a single application. For that reason, Web hosting needs to be portable. Servlets provide that portability. The AS/400 may be the best platform for back-end business applications, but front-end Web applications may not always be on the AS/400.
Web Logic
In specifying a URL on your browser, qualification is often to an HTML file within an explicit host directory: http://yourDomain/ home/level1/level2/SomeHtml.html. The host simply sends the HTML file from the location specified back to the client. Often, for simplicity and security, the host configuration maps a logical directory name to the real directory name, decreasing the length of the URL and concealing the real host directory name. CGI implementations also use the concept of a logical directory by mapping directory name cgi-bin to a library of host CGI programs. When the HTTP server sees cgibin, it executes the program name that follows the cgi-bin qualification. Web servers that support Java servlets, such as IBMs HTTP Server for AS/400, map directory name servlet to a directory of Java servlets. In addition, as with CGI applications, the server invokes the Java servlet qualified by /servlet. Java servlets, like CGI programs, can be invoked from a URL request or as an action item on an HTML form. The page shown in Figure 1, for instance, is qualified by URL http://domainOrIP/servlet/Seminar. Once configured to enable Java servlets, IBMs HTTP Server for AS/400 invokes the Java class Seminar, which is located in the AS/400 Integrated File System (AS/400 IFS)directory/QIBM/ProdData/IBMWebAS/servlets. (For detailed instructions on enabling Java servlets on V4R3 with PTF installation of IBMs WebSphere for AS/400, see WebSphere for AS/400 Setup on AS/400 NetJava Expert Web Edition at www.midrangecomputing.com/anje/99/02. WebSphere V4R4 ships as a free but separately installed program product.)
The browser sends a URL request to the HTTP server in HTTP, which is the protocol of the Web. HTTP browser requests may include embedded HTML files but always provide request methods. When you enter a URL, the HTTP request method is GET, whereas an HTML form request uses the method POST. (For more information on HTTP, see HTTP Undercover, MC, July 1999.) When a Web server receives an HTTP GET request, the servlet engine invokes the doGet method of the Java servlet qualified in the URL. When the server receives an HTTP POST request, such as one sent from the entry form shown in Figure 1, the servlet engine invokes the doPost method of the servlet qualified by the action parameter of the HTML form tag. For example, notice the qualification of the Seminar servlet and the specification of a POST request method in the HTML in Figure 2:
The Servlet API
The example application in Figure 1 uses a Java servlet invoked by URL request http://domainOrIP/servlet/Seminar. The Seminar servlet dynamically builds the HTML response with the latest product information. That HTML response includes a form whose action is handled by the same Seminar servlet (although it can be a different servlet). The Seminar servlet is Java built atop the generic HttpServlet class. HttpServlet provides code implementations for common services, two of which Ive already mentioned: doGet and
doPost. HttpServlets code implementations for doGet and doPost do nothing worthwhile. Theyre in HttpServlet as placeholders to assure the servlet engine that all servlets, if only by order of object-oriented (OO) inheritance, have these methods. This is important because the servlet engine calls the doGet method based on a URL request and calls the doPost based on an HTML form action request.
If your servlet is to process an HTTP GET request from a URL, you must define a custom implementation of HttpServlets doGet method, and if your servlet is to process HTML forms, you must code a doPost.
HttpServlet also has a method called init. The servlet engine invokes a servlets init method the first time that servlet is requested, like an initialization subroutine in RPG. As you know from RPG programs, this initial processing can be handy. For servlets, you may want to code your init method to load a Java Database Connectivity (JDBC) driver and initialize JDBC connections or, if you prefer record-level access, open files as global fields declared in a Java class but not in a method of that class. Those JDBC connections or record-level access file opens then become available to all remote requests, saving the time required to connect to the database.
The Example
Code for the Seminar Java servlet is given in Figure 3. At Label A, the Seminar class extends the HttpServlet class. At Label B, the global fields of the Seminar class are declared. The values of these fields are accessible to all clients. The init method, at Label C, first calls its dads implementation of init. When you override HttpServlets init method, you need to invoke the parents version of init because it does some important initial processing that you need not code yourself. The Seminar classs custom version of the init method then creates a vector (a dynamically sizable array) to hold the registrants. This servlet is coded for simplicity, so pretend that the init function has gone to DB2/400 to obtain the latest seminar locations and counts. Otherwise, I may as well code this information in a static HTML file. Thats the point of servlets: to present dynamic information over the Internet.
As Good as It Gets
The doGet method on Label D in Figure 3 has two parameters: HttpServletRequest and HttpServletResponse. The first parameter contains information about the request; the second contains the dynamically generated HTML response. I suggest you review the Java documentation for these two classes, as they have some powerful capabilities. Both of them, for instance, have methods that make using HTTP cookies a breeze. The request contains any parameter on the URL, but because the Seminar application uses no URL parameters, its implementation of doGet ignores the request parameter. At Label E, however, the response parameter is used. Think of HttpServletResponse as a handle to an HTML file containing the response to the users request. At Label E, the document resp.setContentType (text/html) tells HTTP that this file is to be transferred to that browser as text-based HTML. The next line at Label E receives a handle to the output stream. Its like setting a record format in an RPG screen program.
The doGet method on Label F in Figure 3 dynamically constructs an HTML file. All HTML files are enclosed by and tags. They also have a head
and body , so these obligatory tags are inserted into the response buffer. Label F then builds the body of the HTML file, inserting the .gif file for MCs coffee cup and listing the fall dates for my Java seminars. Again, in a real application, this information comes from a database. At Label G, the input form is constructed. The input form contains a drop-down selection for the city of choice and a text field for the registrants name. The doGet code ends by closing the print writer, at which point the servlet engine sends the HTML response to the browser (see Figure 2).Postage Due
Once the user selects a city, keys in a name, and clicks Register, the ACTION option of the HTML form tag instructs the Seminar servlet to process the HTTP POST request. Code for the doPost method is given in Label H of Figure 3. The doPost method has the same two parameters as doGet. Again, the content type is set, and a handle to the output writer is obtained. At Label I, the city and name parameters specified by the client are retrieved. Then, at Label J, after stuffing the obligatory HTML, HEAD, and BODY tags, doPosts code checks whether registration is full. If seats are still available, doPost increments the array element of the global count field associated with the selected city. (A real application would update a database at this point.) Figure 4 shows the dynamic HTML content generated by doPost when Billy Briggs registers, and Figure 5 shows how it looks on Billys browser.
You Must Pool Your Resources
Obviously, Internet applications are more complex than my Seminar servlet, and industrial- strength servlets have more requirements. They must have some form of transaction control to ensure data integrity. For performance, they should have some form of database connection pooling. They also need a strategy to maintain state across the stateless HTTP. Transaction control can be enabled with JDBC transactions, record-level access commitment control, or Enterprise JavaBeans (EJB) transactions. You can code your own connection pool logic or use the connection pooling features included with most Web application servers, including IBMs WebSphere. For such things as the Internets popular shopping cart metaphor, you can use either HTTP 1.1s Session API or HTTP cookies. You can also add elegant state management features by employing EJB with your servlets. You may ask, Isnt embedding HTML into a Java servlet the same thing as describing screens in RPG? That is a problem. Its always better to separate screen design from program design. Its even more important with Web applications because HTML design is becoming a profession unto itself. Business programmers can easily present information logically with HTML but dont often have the time or training to make it pretty with graphics. Recently, Sun developed Java Server Pages (JSP), which separates programming logic from screen presentation, and because JSP is relatively new, its fortunate that WebSphere supports JSP.
Related Materials
HTTP Undercover, Teresa Pelkie, MC, July 1999
WebSphere for AS/400 Setup, Lisa Wellman, AS/400 NetJava Expert Web Edition, www.midrangecomputing.com/anje/99/02
Figure 2: HTML forms can associate a Java servlet to process the user request.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Seminar extends HttpServlet
{
A G H
I
J
String cities[] = {"Las Vegas", "Kansas City", "Dallas", "Phoenix"};
int count[] = {57, 48, 99, 100};
Vector registrants[] = null;
public void init(ServletConfig sc)
throws ServletException
{
super.init(sc);
registrants = new Vector[cities.length];
for (int i = 0; i < cities.length; i++) {
registrants[i] = new Vector();
}
B D
E
F
C
Figure 3: The Seminar servlet creates a registration form in its doGet method and processes that form in its doPost method.
Registration Confirmation
Thank you, Billy Briggs. Your registration is confirmed.
Figure 4: The HTML response from a servlet contains dynamic information.
resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());
String name = req.getParameter("name");
String city = req.getParameter("city");
out.println("");
out.println("
out.println("");
out.println("Registration Confirmation
");
int iCity = 0;
while (cities[iCity].equals(city) != true)
iCity++;
if (count[iCity] >= 100) {
out.println("Sorry, the seminar is full in "+cities[iCity]);
} else {
count[iCity]++;
registrants[iCity].addElement(name);
out.println("Thank you, "+name+". Your registration is confirmed.");
}
out.println("");
out.println("");
out.close();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());
out.println("");
out.println("
out.println("");
out.println("
"ALIGN=""Top"" WIDTH=500 HEIGHT=200>
");
out.println("
Fall '99 Seminar Dates
");
out.println("");
");
out.println("
out.println("
out.println("
out.println("
out.println("
out.println("
Online Registration
");
out.println("
"VALUE=""Register"">");
out.println("");
out.println("");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{ }
}
LATEST COMMENTS
MC Press Online