Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp .com.

Notice: This material is excerpted from Special Edition Using CGI, ISBN: 0-7897-0740-3. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.

CHAPTER 23-Tips and Techniques for Java

Java has become almost synonymous with Internet programming. New pages appear every day containing Java applets and carrying the cup of coffee icon. The success and popularity of Java and the Web are intertwined. As you'll soon see, Java is an ideal language for Internet applications, combining the power of C and C++ with the platform independence of HTML and Web browsers.

Because of its sudden rise in popularity, tools supporting Java development are limited and relatively crude by today's standards. Although Java is changing rapidly (by the time you read this, there will be several commercial and "free" Java development environment options), the examples presented in this chapter are based on the development tools that have been available from Sun since 1995.

Java has been under development at Sun for several years, stabilizing in 1995. Sun has made specifications, compilers, libraries and other tools available at this site.

This chapter covers the following topics:

Introduction to Java

Rather than jump right into Java CGI and applet development, you should become familiar with Java first. Briefly, Java is an object-oriented, architecture-neutral programming language. Like C++, Java relies heavily on C. This eases the transition that C and C++ programmers must make to Java.

Java is byte-code interpreted. This means that the Java compiler doesn't generate object code that's directly executed by your computer's CPU; instead, these byte codes are executed by a java interpreter. Some Web browsers incorporate java interpreters, allowing you to include Java programs in your Web pages. This feature alone assures Java a place in your Internet programming future.

The following section looks into Java's background-where it comes from and what problems it was intended to solve. Then you'll look at the capabilities and features of the language and the Java environment.

See  "Java," p. xxx, and "Compiled Interpreted Scripting Languages," p. xxx, for more background information on Java. 

The Origins of Java

Understanding the origins of language-particularly a programming language-reveals a great deal about the language itself. What problems encountered with other languages are solved by this new language? Was the language developed to address the specific problems of only a few application areas, or is it general purpose?

Java was developed at Sun Microsystems by a development team, headed by James Gosling, that was developing applications for consumer products. Because the breadth of these applications is large, a language was needed that would operate efficiently and reliably in many environments, on many processors. User interfaces must be simple and intuitive, and the software often interacts with real-world objects.

You may remember James Gosling's previous efforts with the NeWs windowing system and a version of the UNIX editor, emacs.

Although C and C++ are widely available and portable, they have some disadvantages for many consumer product applications. C and C++ are compiled languages that result in processor-specific machine code that must be linked with environment-specific libraries to create a runnable program. If any aspect of this environment changes, the program must be recompiled and relinked. C is loosely typed, allowing the programmer great flexibility but also permitting the introduction of severe bugs that may be difficult to find. Although C++ is object-oriented and addresses some of C's limitations, it has grown large and complex, losing the original simplicity and elegance of C.

In 1990, Gosling began developing a language to meet the needs of consumer product software. Much like the development of the C programming language, Java saw practical use in projects at Sun. Although these projects never resulted in commercial products, they did result in improvements to the language. This has made Java a full-featured, robust programming language with many of the best attributes of C and C++, few of their limitations, and several unique features.

The specification for the Java programming language and the Java Virtual Machine (the byte code interpreter) is open and has been made publicly available by Sun. Sun is also licensing the development and runtime software, and makes the Java sources readily available. The latest updates and availability information is available at this site.

Sun has made sources for Java and Hot Java (Sun's Java browser) available for educational, porting, and non-commercial purposes at no charge, but under obligation to not redistribute. Source code changes (required to port to new hosts) and objects may be freely distributed.

A Brief Overview of the Java Programming Language

Java draws heavily on C and has much in common with C++. Wherever possible, Java uses C syntax. All the basic C types and flow-control constructs are available. It's virtually impossible to distinguish small snippets of Java code from C.

Like C++, Java is object-oriented. Java supports single inheritance with a root class, and inherited functions can be overridden or overloaded.

Overriding an inherited function means that the derived class replaces the base class function with a new function with the same name and arguments. Overloading means that the derived class provides a function with the same name as a function in the base class, with different argument types and a similar function.

Java implements abstract classes with interfaces, which describe how a class can be used without providing any implementation. An object in Java may implement any number of interfaces, and these interfaces are very similar to CORBA IDL interfaces. (CORBA is the Common Object Resource Broker Architecture developed by the Object Management Group (OMG). In CORBA, object interfaces are described in IDL, the Interface Description Language.)

Although similar to C++ in many respects, a major objective of Java was simplicity. Consequently, any feature of C++ that wasn't absolutely necessary was eliminated. There's no multiple inheritance. There are no structs, unions, pointer types, or multidimensional arrays, nor are there header files, templates, or implicit type conversions.

Even though it's simple, Java has added extensions beyond C++. The most significant addition is garbage collection, eliminating memory leaks.

With garbage collection, Java has no delete operator. Instead, the runtime system determines when memory resources are no longer in use and frees the memory. A common bug in C and C++ programs is the memory leak, where explicitly allocated memory isn't freed after use.

Java is staticly typed, allowing for efficient code generation, but also supports dynamic type determination, so that programs can do different things based on the object type. Java has built-in exceptions, so you can write programs that detect and respond to errors, rather than abort, core dump, or cause general protection faults.

Because Java compiles to byte codes that run on a Java Virtual Machine, Java is architecture neutral. Word lengths and byte ordering are defined for the virtual machine and are the same regardless of the underlying machine architecture.

Java is multithreaded, eliminating the need for programs with polling loops that look for user input. Java threads are virtual threads in single processor environments, but may be truly concurrent in multiprocessor machines. Java provides thread synchronization mechanisms to support creating reliable programs using threads.

It's beyond the scope of this section to examine Java in great detail, but an example is worthwhile. Look at a listing 23.1, which is very simple Java program-the ubiquitous "Hello World."

Listing 23.1 HelloWorld.java: The Simplest Java Program
/*
 * HelloWorld.java : the simplest program
 */
public class HelloWorld {
  public static void main(String args[]) {
    if (args.length <= 0) {
      System.out.println("Hello World");
    } else {     // there are command line arguments
      for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
      }
    }
  }
}
/* the end of the (Hello)World */

If you're familiar with C++, you've seen code much like this. Although quite simple, this program demonstrates some of the features of Java, as follows:

A complete discussion of the Java programming language is provided in Special Edition Using Java, published by Que Corporation.

The Java Class Libraries

Like C and C++ before it, Java relies on extensive libraries to create applications. These libraries provide utility classes for creating programs and I/O, so your program can communicate with the world. Although libraries are often considered an integral part of the language, they provide a means of extending the language and adapting applications written in the language to various environments.

Java libraries support basic Java operation, applications and applets, and application I/O, as described in briefly in table 23.1. These libraries are frequently enhanced and updated. A detailed description of the components in these libraries is provided at this site. Table 23.1 Java Libraries

Library Description
java.applet This library provides the base classes for Java applets that execute on a browser.
java.awt This is actually a set of libraries that support Java graphical user interfaces, using the capabilities of the underlying system.
java.io This provides the general input and output capabilities for Java applications, including file and stream I/O.
java.lang This provides base class support for the language, including Strings types.
java.net This provides classes for network I/O.
java.util This is a library of utility classes for Java applications.

The Java Runtime Environment

Java is a compiled language, but rather than compile to object code for each individual computer type, Java compiles to a standard byte code. This code is the same regardless of the particular machine or operating system that the Java application executes on. A Java application that runs on a Sun Sparcstation running Solaris will run on an Intel platform running Windows NT without recompiling.

Platform-independent execution of a Java program requires a Java Virtual Machine to execute the compiled byte codes. As mentioned earlier, the specification of the Java Virtual Machine is open and widely available, encouraging numerous implementations. This virtual machine is provided by every machine and operating system combination that runs Java applications.

Java and the Java Virtual Machine have one requirement previously not common on personal computers: multithreading. Multithreading is not only a feature of the language, but is required for the language to execute. In particular, garbage collection is performed in a separate thread of execution from the application thread. And to be efficient, the underlying system should provide support for multithreading. This is one reason why some systems (or operating systems) don't have Java-compatible browsers or development systems.

Java Applets

Up to this point, I've discussed the Java programming language. Anyone using a computer who hasn't been in a cave for the last year has heard of Java applets. Many people believe that Java is useful only for applets.

But how do applets work? Java applets convert a relatively static presentation of HTML into an interactive system at the browser.

Java applets are incorporated into the HTML sent to the browser by the HTTP server. Once at the browser, the Java applet executes in a runtime environment established by and controlled by the user. This requires that the browser implement the Java Virtual Machine and, in most cases, requires a system that provides some of the necessary execution support, such as multithreading.

Although this isn't an endorsement, the most commonly available browser supporting Java applets is Netscape 2.0+.

Once downloaded and executing, a Java applet is a complete application. The applet can create new windows outside the browser, as well as use space within the current HTML page. The applet has powerful URL capabilities, allowing it to load new pages based on user actions. Java provides powerful networking capabilities, allowing creation of complete client applications that are downloaded as an applet. Such a client can make a direct connection to a server without the overhead of HTTP.

What about security? I may download anything off the Internet and run it on my computer, but you may prefer applications that you know won't destroy data or inject a virus. It would seem that continually downloading applets, possibly without the user knowing, would seem a great risk. While there are known problems with Java security, known solutions are expected to be implemented in the production release. Until then, Java isn't appropriate for sensitive applications.

The Java security model places control of resource access by the applet in the hands of the browser, and consequently the person using the browser. An integral component of the Java runtime environment is the SecurityManager, which checks permissions before any I/O operations, to the Net or the local file system.

The SecurityManager is part of the browser. Most browsers are very restrictive regarding what resources an applet may access. Applets are now restricted to communication with the server from which it came, and they can't access the local file system.

In addition to the security imposed by the browser's SecurityManager, Java provides other support for safe execution in a network environment. Java byte codes are designed to be verified and are less susceptible to covert, malicious modification than ordinary object codes. The lack of pointer types reduces risk of data corruption due to errant accesses (in systems that don't provide adequate process memory protection).

JavaScript

JavaScript is a powerful scripting language that extends the Web browser's capabilities. Developed by Netscape, JavaScript is best supported by Netscape's browser. Unlike Java, which is useful for developing stand-alone applications, JavaScript is tightly coupled with HTML and the browser. Although separate applications can't be developed in JavaScript, JavaScript has access to the objects within the browser itself and is therefore very useful in creating Web applications.

Like Java, JavaScript syntax is much like C, and although new objects aren't created, JavaScript has access to browser objects that represent the portions of the current HTML page. This allows you, as the Web application developer, to extend the capabilities of the HTML processing without requiring interaction with the HTTP server.

See  "JavaScript," p. xxx, for more background information on this scripting language. 

The Java Development Environment

The most widely distributed Java development environment is provided by Sun and consists of compatible but separate tools for compiling the Java sources, and running and debugging the resulting programs. This is much like C was in the early days but is rapidly changing as Sun and other vendors develop integrated environments.

Sun's Java Development Kit

Sun's Java Development Kit (JDK) consists of the following components:

These are all the tools needed to develop Java applications and applets.

Compiling Java Programs and Applets

The first step in creating a Java program is to edit the source files using the editor of your choice. Java source files have the extension .java and the file name should match the name of the class in that file.

It's generally a good practice to put Java classes in separate files, and use the import capabilities of the language to access other classes.

After the sources are edited, the standard compile/run/debug/edit cycle begins. The first step is to compile the Java source code, as follows:

javac HelloWorld.java

Caution

Your CLASSPATH environment variable must include the Java classes. For a typical UNIX installation, this would be: CLASSPATH=./:/usr/local/java/classes.

Assuming there are no compile-time errors, javac compiles the code and creates the file:

HelloWorld.class

This file is run by the Java Virtual Machine. This may be the java interpreter, or the appletviewer or browser, if the program is an applet.

Running Java Programs and Applets

Running a Java program requires running a Java Virtual Machine that interprets the byte codes. The JDK provides a java interpreter, which implements the Java Virtual Machine and is required to run java programs. Java programs are executed using the java interpreter as follows:

java HelloWorld

This produces Hello World on-screen. Arguments are passed to your application by appending them to the end of the previous command line:

java HelloWorld Welcome to the World of Java

This outputs each word after HelloWorld on a separate line.

Environment variables must be explicitly passed to the java interpreter where they're made available to your program. This is done with the -D option to the java interpreter, as follows:

java -D PATH=HOME -D USER=NONE HelloWorld Welcome to the World of Java

The java interpreter accepts as many -D options as necessary.

Previous versions of Java libraries included a getenv() function, similar to those found in C libraries. This has been removed in favor of the -D option to the interpreter.

After you complete your Java program, you can run it on any system that supports the Java byte code interpreter. You won't need to recompile or relink your code. You simply transfer the HelloWorld.class file and run your program.

Because the environment provides the java library set, libraries can be upgraded for bug fixes without recompilation of the applications that they support.

Soon-to-Be-Released Integrated Environments

For those of you who've been around since paper tape and punch cards, the Java Development Kit is quite nice. It's robust, produces good code, and operates well with UNIX makefiles. For the rest of us who have grown accustomed to GUIs and integrated development environments, these tools are a giant leap back in time. Sun and other tool providers are aware of the limitations of the JDK and are working toward providing fully integrated development environments for release this year. Sun will offer the Java Development Environment (not Kit) as a commercial product. This will provide an integrated code and class browser, build manager, and debugger.

Look for major vendors of PC development tools such as Borland and Symantec to distribute their own integrated development environments. Soon everyone will have access to professional Java development tools on their choice of platform, and the code they create will run on all Java-enabled computers!

Creating Java CGI Applications

Java combines the performance and object-oriented features of C++ with the portability and ease of use of typical scripting languages such as Perl. This makes Java an ideal candidate for creating CGI applications. The networking capabilities provided by the Java libraries provides the means for integrating the CGI application with commercial database systems and other distributed applications.

Using Java as a CGI requires the same capabilities of any other CGI program:

The next sections examine some techniques for doing these things with Java.

Executing the Java Interpreter

Because Java applications aren't directly executable by the operating system, the HTTP server can't execute a Java CGI directly. Java CGIs should be executed from a shell script as follows:

#!/bin/sh
CLASSPATH=/usr/local/java/classes:./
export CLASSPATH
java HelloWorld

This not only runs the CGI (in this case, HelloWorld), but also establishes the runtime environment for the java interpreter.

The java interpreter must have knowledge of the locations of the CGI class(es) and the library classes to load the application. Because these vary from machine to machine, or even due to the personal preferences of the system administrator, the Java developers choose to use an environment variable to communicate this information to the java interpreter.

Accessing Standard Input and Standard Output

As demonstrated in the HelloWorld.java example, Java provides simple access to standard output. Access to standard input is provided with an equally simple interface (see listing 23.2).

Listing 23.2 cat.java: Copying Input to Output
/*
 * File: Cat.java
 */
import java.io.*;

public class Cat {
    public static void main(String args[]) {
      int ch;
      try {
            while ((ch = System.in.read()) > 0) {
                System.out.print((char)ch);
            }
        } catch (IOException e) {
            System.out.println("IOException Caught");
        }
    }
}
/* the end of the Cat */

This provides access to an input stream as an array of bytes. This is needed in CGI programs to handle the HTTP character translations necessary when transferring data from the server.

Accessing Environment Variables

System environment variables aren't directly accessible to Java applications. In some environments, these variables don't even exist, and their use varies from system to system. For these reasons, the mechanism provided by the java interpreter for passing these variables is an enhancement. The -D option is consistent across all platforms.

Using your CGI shell script to kick-start the Java CGI requires that you add the -D option to the interpreter command line, as follows:

#!/bin/sh
CLASSPATH=/usr/local/java/classes:./:$CLASSPATH
export CLASSPATH
java -D Client=$CLIENT HelloWorld

This is a simple case of passing a single environment variable with no verification. A production script would add a set of standard environment variables, as well as application-specific variables, and validate each.

The Java application accesses these variables using the System.getProperty() method, as shown in the following snippet:

String clientenvname = "Client";
if (String clientname = System.getProperty(clientenvname) != null) {
    System.out.println(clientname);
}

With access to environment variables, command-line arguments, and standard I/O, Java provides the capabilities to write any type of CGI application. In the next section, you'll look at how applets can improve the power and flexibility of CGI Web applications.

Java and JavaScript Applets

Java is an appropriate choice for your next CGI development effort, but it also provides capabilities for enhancing your existing or new CGI applications. These applets add not only flash to your Web pages, but can increase the efficiency and ease of use for anyone browsing your page. With Java, you can create Web applications that could never be created before.

In the following sections you'll look at how to incorporate Java and JavaScript into your next Web application.

Java Applets

The basic premise of a Java applet is that a small program can be downloaded as a part of your Web page and run on the client system in an environment established by the browser. This application isn't part of the browser any more than a word processor is a part of the operating system that loads and runs it.

What Java applets provide are the capability to create stand-alone or internetworked (using the internetworking I/O capabilities provided in the Java libraries) applications that are delivered to Web users. These applets aren't limited to modification of the contents of a Web page, but can open new application windows on the client, outside the browser.

Java applets can also be cleanly incorporated into your Web page because they're a component of the page and loaded by the browser. This is commonly used for sophisticated animations or presentations of data within the page. Just remember that Java applets don't modify the contents of other regions of the page.

The Web browser controls the execution of a Java applet. The applet is downloaded to the browser based on the <applet> HTML tag in the Web page, as shown in listing 23.3.

Listing 23.3 marble.html: HTML Source Containing a Java Applet
<html>
<head>
<title>
Draw Marble
</title>
</head>
<body>
<center>
<h2>Show a Marble Color</h2>
<applet code="marble.class" width=200 height=200>
Loading marble...
<param name=color value="magenta">
</applet>
</center>
</body>
</html>

When the applet tag is processed, the Java byte code file is downloaded to the browser, where it's executed (see fig. 23.1). Notice that the applet size is controlled by the applet parameters and the position on the page matches the location of the tag in the HTML source.

Fig. 23.1

Java Applets can execute in the browser.

Because all the Java applet parameters appear within the applet tag, any browser that doesn't support Java applets will ignore the applet section.

Any text within the <applet> tags is displayed if the applet can't be run. Tagged alternate text may also be provided and may be displayed by some browsers while the applet loads. Use this to provide feedback to your users.

If your browser doesn't support Java or is simply too slow, use the Java Development Kit appletviewer (see fig. 23.2). This will only run your applet, but requires significantly less resources than most browsers. Notice that the surrounding HTML text is absent.

Fig. 23.2

The JDK appletviewer allows you to view your Java applet.

Parameters can be supplied to your applet and are accessed in the same manner as environment variables in a stand-alone Java application.

Once the applet is downloaded, the browser invokes the applet's init method. This method establishes the initial state of the applet in preparation for execution. Once initialized, the applet is started by invoking the start method. This is done by the browser when the applet first starts and any time the page is revisited but not reloaded. When the browser navigates to a new page, the stop method is invoked, putting the applet in a suspended state. This prevents the applet from unnecessarily using system resources. If the browser unloads the page or exits, the applet destroy method is invoked, freeing any resources used by the applet.

You can customize all these life-cycle methods by overriding them in your applet. The init method is overridden in any applet that accepts parameters.

Now that you know how to load an applet and how the browser should execute it, look at a simple example that draws a marble that changes color (see listing 23.4).

Listing 23.4 marble.java: A Simple Example of Java Animation
/*
 * marble.java
 */
import java.awt.*;
import java.applet.*;

public class marble extends Applet implements Runnable {
    Thread cntrl;
    Chroma sphere;

    public void init() {
        cntrl = new Thread(this);
        try {
            sphere = (Chroma)Class.forName("ColorBall").newInstance();
            sphere.init(this);
        } catch (java.lang.ClassNotFoundException e) {
            return ;
        }
    }

    public void start() {
        if (cntrl.isAlive()) {
            cntrl.resume();
        } else {
            cntrl.start();
        }
    }

    public void stop() {
        cntrl.suspend();
    }

    public void destroy() {
        cntrl.stop();
    }

    public void run() {
        while (true) {
            repaint();
            try {
                Thread.sleep(500);
            } catch(java.lang.InterruptedException e) {
                continue;
            }
            sphere.advance();
        }
    }

    public void paint(Graphics g) {
        sphere.paintColor(g);
    }
}

abstract class Chroma {
    protected Applet app;
    /*
     * init this thread
     */
    protected void init(Applet app) {
        this.app = app;
    }
    public abstract void advance();  // next step
    public abstract void paintColor(Graphics g); // new color, repaint
}

class ColorBall extends Chroma {
    private Color bc = Color.white;
    private int cnum;

    public void advance() {
        cnum = cnum+1;
        bc = new Color(cnum);
    }

    public void paintColor(Graphics g) {
        g.setColor(bc);
        g.fillOval(40, 40, 100, 100);
    }
}

First, notice that the abstract window and applet classes are imported. Then notice that the marble class inherits from the applet class and implements the Runnable interface. Also notice that there's no main.

This applet demonstrates multithreading. One thread draws the marble with new colors; the other performs the timing and control of the applet. This is a rather tame use of threads but serves to demonstrate the underlying capability. Although this applet is very simple, the complete Java class library is available for use in your applets, allowing you to write sophisticated, interactive applications. Visit a few of the sites listed at the end of this chapter for a test drive.

JavaScript Applets

JavaScript lacks many of the sophisticated features of Java-such as multithreading and some I/O capabilities-but it's highly integrated with the browser objects. This gives JavaScript access to Web page elements and the capability to modify variables.

JavaScript is downloaded as a part of your HTML page and is processed as it's received. If your script has a syntax error, it will be detected by the browser and you'll be alerted. Because JavaScript has many of the features of other scripting languages (Perl or C-shell), writing JavaScripts not only is easier than writing HTML, it's more fun.

JavaScript can't change what's already on the page. JavaScript can, however, open other windows for new output.

JavaScripts consist of functions that are called as a result of browser events. You define these functions directly within your HTML and make individual associations with specific events. You may choose to associate a function with a button click so that form validation may be performed. Listing 23.5 shows an example of this.

Listing 23.5 colorform.html: Validating Form Input with JavaScript
<!-- Simple color selection form with JavaScript validation
 -->
<HTML>
<HEAD>
<script language="JavaScript">
<!-- hide script from old browsers
  function checkcolor() {
    if (document.sel.color != "blue") {
      alert("Any color you want so long as it is blue!");
      return false ;
    } else {
      document.sel.submit();
      return true ;
    }
  }
// end hiding contents -->
</script>
<TITLE>
Simple Color Selection
</TITLE>
</HEAD>
<BODY>
<center>
<h2>Select a color</h2>
<FORM NAME="sel"  onSubmit="alert('Your color choice has been selected.')">
<p>Color: <INPUT TYPE="text" NAME="color" Size="20" >
<p><INPUT TYPE="button" VALUE="I Like This Color" onClick="checkcolor()">
</FORM>
</center>
</BODY>
</HTML>

Note

Some browsers may not implement comments correctly, and your JavaScript applet may appear as garbled information-screen.

When this page is loaded into the browser, it appears as a regular HTML form (see fig. 23.3). The difference between the JavaScript form and a normal form becomes apparent on input. When a color value is submitted, the JavaScript function is invoked and the value is validated.

Fig. 23.3

A JavaScript applet executes as part of a form page with an error alert.

Put JavaScript functions in the HTML <head> section of your document to prevent a call to a function before it's loaded.

All the objects within the Web page are accessible to the JavaScript applet. For example, the HTML page above contains a FORM named sel containing an input variable named color. The value of this input variable in the FORM is accessed with this line in the script:

if (document.sel.color != "blue") {

document refers to the entire Web page and sel is the name of the form. The specific form variable, color, matches the name given in the HTML form.

Notice that the input type of button is used rather than submit. This is because the verification function actually performs the form submission. If a submit button was used, the form would always be submitted. This script produces a browser alert in a separate window when an error is detected.

JavaScript can also produce output directly within the Web page. This can be used to produce messages or warnings without the overhead, or extra mouse click to dismiss, an alert window. You might also find this useful in sophisticated, interactive applets where most of the output is from the JavaScript.

The output from a JavaScript that appears on your browser display won't print out on a printer.

JavaScript functions accept parameters without specific type declarations in the function definition. This allows you to write general-purpose functions (such as a date entry validation function) that can be used in many locations within your page.

You must be careful with quotation marks and function arguments. Either switch between single and double quotation marks, or escape out double quotation marks when a JavaScript function is the target of a FORM action.

Using Java with JavaScript

It might seem that using Java and JavaScript is an either-or proposition, but each has its place in Web-enabled applications. In fact, when they're used together, the relative strengths complement each other quite well. JavaScript's tight coupling with the browser makes it ideal for client-side applications that communicate data back to the HTTP server, whereas Java's robustness and efficiency makes it ideal for client-side applications that require fast interaction and animation.

With a combination of JavaScript and Java, it's possible to produce Web pages with unprecedented capabilities with only a single access to the HTTP server. It's now possible to create a single Web page that contains a form for the selection and purchase of a product, and simultaneously allows the product to be examined. This page would use JavaScript to validate selections, and a Java applet would allow the customer to examine the product, viewing it from different angles and changing characteristics such as color and size. All of this can be done without additional access to the HTTP server.

Integrating Applets with Traditional CGI Applications

JavaScript has immediate application with traditional CGI due to its capability to enhance the integration of the Web page with the operations of the browser. Also, JavaScript can be used to jazz up a page with simple animations, making your site more attractive to Web surfers.

JavaScript enhancements to your site can be made with no additions to the CGI back end of your site. In fact, if you use JavaScript for form entry validation and your CGI application also performs validation, you shouldn't change your CGI. Because not all browsers support JavaScript, you'll need the CGI form-validation features for those clients. The JavaScript-capable browsers will always send back validated entries.

Java isn't as well integrated into the browser and is less appropriate for browser-oriented tasks, such as form entry validation. However, Java is a programming language and environment that supports development of sophisticated animations and complete, self-contained or networked applications. Visit almost any of the Java sites to see the kinds of animations capable with Java.

Non-animation Java applets can include the following:

With Java, you can now supply a financial calculator applet with your loan application and amortization Web page.

Advanced Client-Server Applications

One of the most exciting features of Java is its network I/O capabilities. Java has access to traditional TCP/IP network communication facilities that allow you to create client/server applications that use these technologies to transfer data.

The implementation of the Java SecurityManager allows the browser control over the communications services available to a Java applet.

We'll soon see powerful client/server applications on the Internet that use the browser for application navigation and applet download. These applications will transfer large amounts of data directly to the server-side application from the client without using the HTTP server.

Issues and Tradeoffs Related to Java

As relatively new technologies, JavaScript and Java are both undergoing development and change as their use increases. These changes continually improve the languages and most are backward compatible, so your old applications will continue to work. However, this lack of stability is a concern to many and cautious developers might take a wait-and-see attitude rather than commit significant development resources to such new technology.

Another issue is that not all browsers support Java and JavaScript. For intranetworks this isn't serious problem, although it may be a serious cost. In these cases, it's often acceptable to require the use of a particular browser. In cases where the service is provided to the general Internet audience, some consideration must be given to the users who don't have a Java-capable browser. Serving such a broad constituency can be costly and add to the complexity of the CGI application, which must alter the outgoing HTML based on the browser capabilities. This should be a serious consideration to anyone attempting commercial Web applications.

JavaScript source is an integral component of the HTML page sent to the browser. As such, it's accessible to anyone who accesses your page. Many mainstream commercial developers are uncomfortable with the prospect of "giving away" source code. In most cases, they're new to the Internet and not yet accustomed to the spirit of sharing that is its foundation.

Links Related to this Chapter

As Java and JavaScript become increasingly popular, Internet sites are springing up with support for users and programmers. You'll find many sites with tutorials and examples to simplify your use of this technology. Others will simply entertain. Listed here are a few sites to get you started:

QUE Home Page

For technical support for our books and software contact support@mcp.com

Copyright ©1996, Que Corporation