Alternative to CGI -

milklivereddeepInternet and Web Development

Nov 13, 2013 (3 years and 1 month ago)


Alternative to CGI -
JDBC Servlet
By John Kirby
Dynamic Information Systems Corporation. (DISC)
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 1
Trying to decide how to implement a web database application?
Or need to access your legacy data via the web?
Solving these challenges has traditionally been done through CGI (Common Gateway Interface)
scripts. A CGI database script is nothing more than an external program run by the web server to
access the database and create output in the form of an HTML document for presentation on a web
client. This is a proven architecture but has three major limitations:
 Difficulty in maintaining session state
 Performance bottlenecks
 Can involve proprietary APIs
These limitations can create significant problems when trying to develop enterprise based web
There is a new architecture that not only solves these problems, but also gives code portability and
the ability to allow your server-side application to interface with a wide range of relational
databases. That architecture is using JDBC with Java servlets to replace CGI. JDBC (Java
version of ODBC) is a Java based API that is now a standard part of Java and is included in the
Java Development Kit 1.1. Servlets are the server side Java counterpart to applets without a
graphical user interface. They are protocol-and platform-independent components, which extend
Java-enabled web servers (e.g., Netscape, IIS). Servlets allow state, can use a standard database
API (JDBC) and have a significant performance increase because they have no heavy process
startup and initialization for each client request like CGI.
Maintaining State and Sessions with Servlets
A typical CGI architecture uses cookies on either the client or server (or both) to maintain some
sense of state or session (a session is a series of requests from the same client that occur during a
given time-period). This cookie technique however doesnt solve the problem of keeping the
connection alive between the CGI application and the database. You are still required to re-
establish or maintain a connection during a client session. This is required because CGI
applications are forked processes, which are spawned for each client request, then die.
Servlets, on the other hand, can maintain state and session identity because they are persistent and
all client requests are processed until the servlet is shut down by the web server, or explicitly
through a destroy method. A servlet technique I use to maintain state/session is through creating a
threaded session class or object (there is a similar feature also available in Suns Java Web Server
1.1). Each client request is stored and maintained in the servlet. When a client first makes a
request, the client is assigned a new Session object and a unique session ID. These values are
stored in a servlet hash table. When the client issues another request, the session ID is passed
(always) and the session object information is retrieved to re-establish session state. A time-out
thread object is also created for each session to monitor when a session times-out due to session
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 2
Servlet Performance Advantages over CGI
The biggest performance feature of servlets is that they do not require the creation of a new process
for each request. Servlets support threads, so there can be one servlet invocation to support
multiple clients. In the web server environment, servlets can run in parallel within the same process
as the server which provide significant performance advantages over CGI. This is because servlets
only require lightweight thread context switches. CGI requires heavier weight process startup and
initialization code on each request. Servlets contain an initialization method that allows for
expensive processes such as database connections to be performed only once at servlet start-up
time. This means that all of the client requests to a servlet can share global resources and take
advantage of caching. Java is scaleable to take advantage of additional processors, so your
servlets throughput and response time can improve on more powerful servers.
JDBC Standard
Most data-centric CGI applications incorporate a proprietary native database API using C/C++ or
Perl. From a programming perspective, this may be fine if you only have one database to deal
with. What happens if you change database vendors or you want to develop an application that
uses data from different databases? Doable but not pretty. A better approach is to use a standard
like JDBC. JDBCs main advantage is that you can develop an application (in Java) that can
interoperate with multiple datasources. JDBC has the same advantages and disadvantages of
ODBC and can be easily incorporated into your servlet.
Servlet Advantages Over CGI
Servlets only need to be loaded once, while CGI programs need to
be loaded for each client request. The servlet has an initialization
method that allows resource intensive actions such as database
connections to be performed at startup and then reused across
multiple client requests. Java is scaleable to take advantage of
multiple processors.
Servlets can run on any platform that supports the Java Virtual
Machine (JVM). PERL scripts can usually be moved from platform
to platform, but CGI and server extensions written in C are not as
Servlets are persistent and can maintain state. CGI programs use
cookies that dont maintain connectivity to the database.
Java is a robust, fully object-oriented language. Java servlets can
utilize Java code from any source.
JDBC Servlet Architecture
As mentioned before, servlets are server side components that extend Java-enabled servers. They
provide a framework for a variety of network based services. These services can include building
dynamic HTML pages on the fly, proxy services, or they can be clients to other services. Servlets
that are database aware can provide a distributed application solution and connectivity through
JDBC in a multi-tier architecture.
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 3
As an example, suppose you want to access your legacy data using a 3-tier architecture. The 1st
tier (client) could be any browser (Netscape, Microsoft IE). The 2
tier would contain the Java 
enabled web server and the JDBC driver. The JDBC driver could also utilize the JDBC: ODBC
Bridge so you can use your favorite ODBC driver with JDBC. Be careful on your choice of
ODBC Drivers. If the ODBC driver is not re-entrant, you could run into some thread issues with
Java. The 3
tier would contain your database.
The servlet in this scenario provides the generation of dynamic HTML, communication with the
client, and database IO through JDBC.
JDBC Servlet Architecture
Client (Browser)
Java Web Server
JDBC Servlet
JDBC Driver
Database Management System (DBMS)
Getting Started With Servlets
To develop and deploy servlets, you will need some software. At the present time, only Windows
NT 4.0 and Solaris are the supported platforms. This means you will have to implement a 3-tier
architecture (NT for the middle tier) to access your data in the HPUX or MPE environments.
A Java enabled web server allows your web server (Netscape, IIS, Apache) to execute servlets via
the servers API (e.g., NSAPI, ISAPI). This involves installing the Java Development Kit (JDK
1.2) which contains the Java Servlet extension to allow your server to become servlet aware. The
JDK can be downloaded from JavaSoft ( You can also
use an Integrated Development Environment (IDE) that supports JDK to speed up the development
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 4
time. I personally prefer Symantec Visual Café, but there are other nice IDEs such as IBM
VisualAge for Java, JBuilder from Borland, and Microsoft Visual J++. Current releases of these
IDEs only come with the JDK 1.1, so you will have to update your classes with the 1.2 release.
If you do not have a web server, JavaSoft has the Java Web Server (JWS). JWS is a web server
written in Java and is easy to install and administer. JWS is free for a 30-day evaluation ($295 to
purchase) and can be downloaded at (
If you have an existing web server, Live Software ( has free software
called JRun. JRun comes complete with the JSDK and JRE (Java RunTime Environment) and a
Windows program to configure your web server. JRun supports Microsoft's Internet Information
Server 3.0 and 4.0, Netscape's FastTrack and Enterprise Server 3.0, Microsoft's Personal Web
Server, and O'Reilly & Associates' WebSite Pro 2.1.
Writing Your First JDBC Servlet
To demonstrate how to build a JDBC servlet, we will use a simple example to illustrate the basic
servlet framework. This servlet will generate a call to the database and return data in the form of
All servlets are built by extending a basic Servlet class and defining Java methods to deal with
incoming client requests. This sample servlet will extend the HttpServlet class that understands the
Web's HTTP protocol and handles most of the underlying "plumbing" required for a Web
After being loaded, three main methods are involved in the life cycle of a servlet:
Servlets are activated by the server through an initialization method call (init()). In a JDBC
servlet, this is typically where database connections are made and other one time expensive
processes are initiated.
Service Calls
After initialization, servlets are then capable of handling many requests through a single servlet
instance. Each client request generates one service call and they can be concurrent. In a JDBC
servlet, the service calls process incoming name/value pair information from a browser, and returns
output as raw data or HTML pages (dynamic or static).
Servlet Termination
Requests are processed until the servlet is explicitly shut down by the web server or through a
destroy method (destroy()). A destroy() could also be called in a JDBC servlet to take care of any
database housekeeping such as closing connections if they are not performed in service call.
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 5
Sample JDBC Servlet Application
public class DBServlet extends HttpServlet {
private Connection con;
public void init(ServletConfig conf) throws ServletException {
con =DriverManager.getConnection("jdbc:odbc:testdata", "", "");
}catch (ClassNotFoundException e) {
throw new UnavailableException (this,
"Couldn't find class: " + e.getMessage ());
}catch (SQLException se){
System.err.println(SQL Exception caught:  + se);
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
try {
ServletOutputStream out = res.getOutputStream();
out.println("<title>Sample JDBC Servlet Demo</title>");
out.println("<body >");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select CustName from customers");
while( {
} catch(SQLException e) {
out.println("An SQL Exception was thrown.");
} catch(IOException e) {
out.println("An IOException was thrown.");
public void destroy(){
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 6
Installing The Servlet
Once the servlet has been successfully compiled, it is ready to be moved to an executable directory
under the web server root. This directory is usually called servlet. The servlet directory contains
all trusted servlets and can be accessed through a URL: The servlet can be configured to be
initialized when the web server starts-up or when the first client access its URL.
JDBC Servlet Breakdown
When the servlet is loaded by the web server, the init() method is invoked. In this example, two
processes occur; registering the JDBC driver class and connecting to the database. The
Class.forName method registers the JDBC:ODBC Bridge class that is included in the JDK
distribution. For this method to work, the JDBC Java class you use must be located in one of the
Java CLASSPATH directories.
The getConnection method opens a connection to the JDBC URL of the database. JDBC URLs
provide a unique way of identifying databases. The format is jdbc:drivername:databasename. In
this example, the driver is odbc, and the database is an ODBC datasource named testdata. The
other two getConnection parameters are user name and password.
con =DriverManager.getConnection("jdbc:odbc:testdata", "", "");
If the registration and connection were successful, then the servlet is ready to service requests.
The service method provides both input and output streams between the client and the servlet. In
this example, when the client executes a request, the service processes the request and the servlet
begins to build the dynamic HTML.
The first step in building the HTML is to set the content type (res.setContentType("text/html"). An
output stream is then established (ServletOutputStream out = res.getOutputStream()). Once the
output stream is created, the servlet starts building the HTML head and body components.
A statement is then created. The statement is used to execute an SQL query which returns a result
set. The result set is then used to display data returned by the query.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select CustName from customers");
while( {
Once the result set display is completed, the result set and statement are closed.
Alternative to CGI - Developing JDBC Servlet Applications
Dynamic Information Systems Corporation 7
This example shows a persistent connection to the database so subsequent client requests do not
require a re-connection. When the servlet is shut down by the web server, the destroy() method
will be called and the connection closed.
Be Thread Safe
Even though the servlet architecture supports threads, it is the responsibility of the programmer to
ensure that each servlet application is thread safe. All variables defined outside the service()
method are bound to the instance of the servlet and shared across all clients. Methods and
variables which need to be bound to each client should be initialized from <B> within </B> the
service method.
Now that we have written and deployed our first servlet, how secure is it? In our JDBC example,
the servlet has access to HTTP-specific authentication data and if it is used with secure protocols
such as SSL, peer identities can also be determined. Like all Java environments, there is a Security
Manager to control servlet activities. By default, all servlets loaded over the network are
untrusted, and are not allowed to perform operations such as accessing local files. Only those
servlets located in the servlets directory are fully trusted and granted all privileges. Servlets that
have been digitally signed in Java Archive (JAR) files can be trusted and granted more permissions
by the Security Manager. A digital signature indicates that the organization which signed the
code "vouches for it" in some sense. It is, as always, up to the server administrator to determine
what level of security you wish to implement.
JDBC ServletsReady for the Enterprise?
Through all the hype Java has been through, server-side Java really promises to deliver solutions
for the enterprise. Unlike the client-side (applets) Java that has to contend with constantly
changing Java Virtual Machines (JVM) because of the browser wars, the servlet environment
offers more stability. You can standardize on your server platform(s), JDK, and use JDBC to
provide a framework to access your data. With the advent of server-side components like
Enterprise Java Beans (EJB), vendors will soon be releasing tools to improve the productivity of
building server based data-centric applications. Servlets will be a part of that architecture.
CGI - you served us well long live servlets!