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 HTML, 2nd Edition, ISBN: 0-7897-0758-6. This material has not yet been through the final proof reading stage that it will pass through before being published in printed form. Some errors may exist here that will be corrected before the book is published. This material is provided "as is" without any warranty of any kind.

Chapter 26 Java[tm] and JavaScript[tm]

by Stephen R. Pietrowicz

@Sun Microsystems's object-oriented programming language Java(tm) and the jointly developed JavaScript are both creating a lot of interest on the Web. You can use Java and JavaScript to create dynamic, interactive Web pages. This chapter gives you a brief introduction to both Java and JavaScript and explains how you can use both of these technologies in your own Web pages.

How @Java Got Started

In 1991, Sun started the "@Green" project to create intelligent @consumer electronics devices. James Gosling, an engineer at Sun, created a new object-oriented language, called Oak, to support the project. He intended to create a language that could be used to write programs for devices like @cellular phones and @television remote controls. Instead of pre-programming the devices before they left the factory, Oak programs could be downloaded as they were needed. When new features were added, the customer would be able to take advantage of them right away without having to send the device back to the factory. In 1993, Sun built prototypes of remote controls using this technology, and although it was promising, they were having problems gathering support from other vendors. On top of everything else, they found that "Oak" was already in use as a trademark.

In 1994, the @Internet and the @World Wide Web experienced explosive growth. The @Oak team began to realize their @downloadable technology could be applied to the Web. They decided to begin work on a new Web browser that would showcase their work. They also renamed the language "Java," a slang word for coffee, a beverage that many engineers drink every day.

Up until that point, @Web pages consisted of @static images and text. A few interesting examples of complex server-side @imagemaps and @CGI scripts did show up on the Web to create simple @paint programs, for instance, but they weren't really interactive. Requests still had to be sent back to the server, and these requests created additional load on the machine serving the documents.

A browser with the ability to download programs and run them on the client machine would offload the server, allowing it to serve more documents. That's exactly the sort of browser the Java team decided to build.

The Java team's browser, HotJava, was the first program capable of automatically loading and running Java programs. HotJava created quite a bit of interest in @Java on the Web, and many companies have licensed @Java from Sun so that they can incorporate the technology into their own products. Some of the same @consumer electronics companies Sun tried to interest with the @Green project are now contacting them to license @Java.

Java has proven to be so popular that on January 9, 1996, Sun spun off a new @business unit called Javasoft that will concentrate on @Java development.

Getting Started with Java

The Java language is object oriented and very similar to C++. It was designed to take many of the best features of C++ while simplifying it to make writing programs easier.

Programs are normally created to run on only one type of operating system. @Windows 95 programs have been specifically created to run on systems running the @Windows 95 operating system, and will not run on the @Macintosh or on a @UNIX system. Java programs, however, are intended to be platform independent. @Java programs are compiled into a series of @bytecodes that are interpreted by a @Java interpreter. After a Java program has been compiled, it can run on any system with a Java interpreter. You do not need to recompile it.

This capability makes @Java an ideal language for programs on the Web. With so many different systems on the Web, creating programs that will work with all of them is very difficult. Because Java programs are platform independent, programs are no longer restricted to running on one platform. They can run on any platform to which Java has been ported.

Java has been ported to many different platforms. Sun has ported @Java to Solaris, @Windows NT, @Windows 95, and the @Macintosh. Other companies have ported @Java to @Silicon Graphics IRIX, @IBM OS/2, @IBM AIX, and Linux.

Using Java Applets in Web Pages

@Java programs that can be embedded into @WWW pages are called @Java applets. To run applets from Web pages, you must have a browser that supports Java, such as HotJava or Netscape 2.0.

If you want to write your own Java applets, you should download the Java Development Kit from Javasoft. It's available for free on the Web. You can download it from the Javasoft Home page:

http://www.javasoft.com

Now take a look at a few examples. Listing 26.1 shows the code for a simple Java applet. This listing is called HelloWorld.java on the CD-ROM.

Listing 26.1, A "Hello World" Java applet.

import java.applet.*;
import java.awt.*;

class HelloWorld extends Applet {

     public void paint(Graphics g) {
          g.drawString("Hello World!",20,20);
     }
}

When you place this applet into a page and run it, it prints Hello World!. But before you can use it in a page, you must compile the applet using javac, the Java compiler. The files that Javac creates are called Java class files. A class file is the platform-independent object file that the browser retrieves when downloading a Java applet.

To use this applet on an HTML page, you have to describe it using the APPLET element. Figure 26.1 shows an @HTML page that loads this example applet.

Fig. 26.1

An HTML page with an applet definition.

The <APPLET> and </APPLET> tags act as a container for the Java applet definition. They indicate to the browser that a Java applet should be loaded. The @CODE attribute tells the browser which Java applet should be downloaded. The browser reserves space in the page using the WIDTH and @HEIGHT attributes, just as it reserves space for the IMG element. Then the browser downloads the @Java class specified in the @CODE attribute and begins running the applet.

In this case, the applet being downloaded is HelloWorld, and it reserves a space 150 pixels high and 200 pixels wide in the page. Figure 26.2 shows what the page looks like when the browser loads it.

Fig. 26.2

A simple Java applet.

Browsers that can't display Java applets don't display anything when this page is loaded. To prevent this situation from happening, you can place HTML markup or text between the <APPLET> and </APPLET> tags. Browsers that can't display @Java applets display the @HTML markup instead. You can use this approach to tell visitors to your pages what they would have seen if the applet had loaded.

Browsers that can display applets don't display any of this @HTML markup. Figure 26.3 shows an @HTML page with alternative @HTML markup.

Fig. 26.3

The @HTML markup in the @APPLET container is shown by browsers that cannot display @Java applets.

Figure 26.4 shows how this page looks in a browser that doesn't support @Java applets.

Fig. 26.4

Instead of showing the Java applet, the HTML text is displayed. This way, you can alert visitors to your page about what they're missing.

You aren't restricted to writing Web applets with Java. You can write full applications with it as well. The @HotJava browser and the @Java compiler are both written in @Java.

The CODE, WIDTH, and @HEIGHT attributes of the APPLET tag are all required. You also can use other attributes in the APPLET tag. Table 26.1 shows the attributes available and their functions.

Table 26.1 APPLET attributes and their functions.

Attribute Function
CODE Defines the applet class to load. (required)
WIDTH Defines the width in pixels of the area in the HTML page to reserve for the applet. (required)
HEIGHT Defines the height in pixels of the area in the HTML page to reserve for the applet. (required)
ALT Defines the alternate text to display if the applet tag is understood, but applet loading is turned off or not supported.
CODEBASE Defines the directory where the classes for the applet are stored. If this attribute is not specified, the directory of the HTML page is searched.
NAME Defines the name of this instance of an applet. This attribute can be used by an applet to find another applet on the same page.
ALIGN Defines how this applet is aligned in the HTML page. Any of the ALIGN options discussed in previous chapters are legal here.
VSPACE Defines how many pixels of space are reserved above and below the applet.
HSPACE Defines how many pixels of space are reserved on either side of the applet.

Listing 26.2 shows a more complex applet called URLsound. (This applet is called URLsound.java on the CD-ROM.) It displays an image with which a user can interact. When the user moves the mouse pointer over the image, this applet changes to another image and plays a sound. When the user clicks on the image, the applet causes the @Web browser to go to a new URL.

If you have loaded a background image or changed the background color and used an applet, the area reserved for the applet will be drawn with the browser's default grey color.

Listing 26.2, The URLsound Java applet.

import java.awt.*;
import java.applet.*;
import java.net.*;

/**
 * URLSound - This applet displays an image in a page. If the mouse cursor
 * moves over the image, it changes to an alternative image, and
 *      a sound is played. If the image is clicked, the browser
 * changes to another page. The images, sound and new page are
 * all user definable.
 */
public class URLsound extends Applet {
     String sound;
     String href;
     Image image1, image2, current;

     public void init() {
          /*
           * retrieve parameters given to the applet on the HTML page
           */
          String pic1 = getParameter("picture1");
          String pic2 = getParameter("picture2");
          sound = getParameter("sound");
          href = getParameter("href");

          /*
           * The MediaTracker class is used to ensure the images
           * have been loaded before we attempt to use them.
           */
          MediaTracker tracker = new MediaTracker(this);

          try {
               image1 = getImage(getDocumentBase(), pic1);
               tracker.addImage(image1, 0);

               image2 = getImage(getDocumentBase(), pic2);
               tracker.addImage(image2, 0);
          } catch (Exception e) {
          }

          try {
               tracker.waitForID(0);
          } catch (Exception e) {
          }

          current = image1;

     }

     /*
      * This routine is called each time the mouse enters the
      * applet area. It plays a sound and changes the displayed
      * image.
      */
     public boolean mouseEnter(Event evt, int x, int y) {

          /*
           * Try to play the sound
           */
          try {
               play(getDocumentBase(), sound);
          } catch (Exception e) {
               System.out.println("Unable to play Sound");
          }

          /*
           * Change "current" to the alternate image and force a repaint
           */
          current = image2;
          repaint();
          return true;
     }

     /*
      * This routine is called each time the mouse leaves the
      * applet area. It restores the initial image and forces
      * a repaint.
      */
     public boolean mouseExit(Event evt, int x, int y) {
          current = image1;
          repaint();
          return true;
     }

     /*
      * This routine is called each time the mouse is clicked in the
      * applet area. It causes the browser to jump to the specified
      * URL.
      */
     public boolean mouseDown(Event evt, int x, int y) {
          URL hrefURL = null;

          try {
               hrefURL = new URL(href);
               getAppletContext().showDocument(hrefURL);

          } catch (Exception e) {
               System.out.println("Couldn't go to URL");
          }

          return true;
     }

     /*
      * The paint method is what actually displays the image.
      */
     public void paint(Graphics g) {
          g.drawImage(current, 0, 0, this);
     }

}

You can customize URLsound to allow you to specify which images to display, which sound to play, and which URL to jump to. You do so by using the PARAM element inside the APPLET container.

@Version 1.0 of the Java Development Kit, the toolkit that programmers use to write Java programs, supports sound files only in @Sun's AU format. If you want to use sound in your Java HTML pages, you must convert the sounds to the AU format.

Figure 26.5 shows an @HTML page that uses URLsound twice, with different parameters.

Fig. 26.5

You can change parameters in the URLsound applet to customize it.

The <PARAM> tag has two required attributes: NAME and VALUE. When an applet initializes, it requests the parameters it's expecting by using the specified NAME, and it receives the VALUE. More than one parameter can be passed to an applet if you put more than one <PARAM> tag in the APPLET container. Parameters that the applet does not recognize are ignored.

In figure 26.5, the URLsound applet takes four parameters: picture1, picture2, sound, and href. picture1 names the picture in its inactive state. picture2 is revealed when the @mouse pointer moves over the picture area, and the @audio file specified by sound is played. When the user clicks the mouse on the picture, the browser jumps to the URL specified by @href. In figure 26.6, a browser shows this page.

Fig. 26.6

Two copies of URLsound in one page.

Special server software is not needed to serve @Java applets. You can use your Internet server provider's current Web server to serve Java applets.

JavaScript

JavaScript is a @scripting language that was jointly created by Netscape and @Sun. JavaScript programs are not compiled like @Java applets. @JavaScript programs are embedded in the @HTML markup of a page. After the page is loaded, the browser interprets the JavaScript program and runs it.

Figure 26.7 shows an example of a JavaScript program.

Fig. 26.7

A simple JavaScript program in an HTML page.

The <SCRIPT> and </SCRIPT> tags enclose JavaScript programs. The required @LANGUAGE attribute tells the browser what type of @scripting language to use. In this case, it uses "JavaScript". If the browser supports more than one language, the @LANGUAGE attribute indicates which language is being used. Figure 26.8 shows this page after it has been loaded into a browser.

Fig. 26.8

The results of the simple JavaScript program.

In chapter 24, you learned that you can use forms and CGI scripts to create interesting programs with which a visitor to a page can interact. One of the problems with CGI scripts is that they require the Web server to execute the script. The additional workload on the server causes it to slow down, especially on a busy server with many CGI scripts. You might have noticed this slowdown when trying to connect to a site that takes awhile to transmit a document. Every time a CGI script runs, it uses valuable resources that could be used to serve more documents.

JavaScript solves the problem of overburdened @Web servers. Instead of writing a @CGI program that must be executed by the server, you can write and transmit a JavaScript program with the HTML page. The client browser, instead of the server, then executes the JavaScript program.

The @HTML page in listing 26.3 contains a @JavaScript program to convert between the Celsius and @Fahrenheit temperature scales. The result of loading this page is shown in figure 26.9.

Listing 26.3, A JavaScript program that converts temperature scales.

<HTML>
<HEAD>
<TITLE>Temperature Converter</TITLE>
<SCRIPT LANGUAGE="JavaScript">

function c2f(form) {
     celsius = form.celsius.value;
     form.fahrenheit.value = (celsius*1.8)+32;
}

function f2c(form) {
     fahrenheit = form.fahrenheit.value;
     form.celsius.value = (fahrenheit-32)/1.8;
}

</SCRIPT>
</HEAD>
<BODY>
<FORM>
Celsius value
<INPUT TYPE="text" NAME="celsius" SIZE=15>
is
<INPUT TYPE="text" NAME="fahrenheit" SIZE=15>
degrees Fahrenheit.
<br>
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="c2f(this.form)">
<br>
</FORM>
<FORM>
Fahrenheit value
<INPUT TYPE="text" NAME="fahrenheit" SIZE=15>
is
<INPUT TYPE="text" NAME="celsius" SIZE=15>
degrees Celsius.
<br>
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="f2c(this.form)">
<br>
</FORM>
</BODY>
</HTML>

Fig. 26.9

The @JavaScript program is loaded, and the fields have no initial values.

The code between the <SCRIPT> and </SCRIPT> elements defines two functions, c2f and f2c, which are used to calculate temperatures. Notice that neither of the functions produces any output. How are these functions used?

The answer is farther down in the document. The ONCLICK attribute of the <INPUT> element is used to execute a JavaScript function, or series of JavaScript statements. In the first form, the function c2f is called. In the second form, the function f2c is called. The parameter to the function call in each of these forms is this.form. All the values in the form are passed to the functions, which interpret the values that the user types into the forms and perform the calculations.

Another thing you may have already noticed about this page is that the JavaScript code is loaded in the HEAD container of the document. Loading the code this way is important so that you can assure the JavaScript functions are loaded before the rest of the page is loaded. This way, you can prevent a user from accidentally trying to interact with a JavaScript program before it is fully loaded. If the user were to press a button before all the functions were loaded, he or she would receive an error.

Figure 26.10 shows the results of @typing values in each of the temperature fields and pressing the Calculate button of each form.

Fig. 26.10

The @JavaScript program computes the temperature values after the values 25 and 32 are entered and the Calculate buttons are both pressed.

This section gives you only a brief introduction to JavaScript. See the "Web Resources" section at the end of this chapter for additional JavaScript information.

Java Security

Security should always be of primary concern to you when you download programs into your system. If Java applets are automatically downloaded and run, should you be concerned that you might download a virus?

Fortunately, the answer is no. @Security mechanisms built into the @Java class structure allow browsers to prevent @Java applets from doing anything malicious to your system.

You don't have to worry about having viruses installed or having your private @financial files stolen through @Java because @Java applets that your browser loads from the Web can't read or write files on your hard drive. The security policy in the browser prevents it.

Because files can't be read, Java applets can't start other programs you may already have installed on your system. No need to worry about a rogue applet coming in and wiping out your hard disk.

@Java applets can create their own windows outside the browser, however. This could be a problem, too. What if the applet you download looks exactly like another program you already have on your system? What's to prevent you from entering data, like a password, into the applet that you're trying to protect?

Java takes care of this situation, too. To prevent you from thinking that these windows were created by your own system, an applet's window is labeled so that you know a Java applet has created the window. This label cannot be overridden by the Java applet, so you know it is always displayed. Figure 26.11 shows a labeled applet window.

Fig. 26.11

Windows outside the browser contain the words @Untrusted Java Applet Window at the bottom of the window.

If you ever see an unexpected window on your screen with the words "Untrusted Java Applet Window, asking for your password, DO NOT type your password. It's likely that someone is trying to use a Java applet to get your password to break into your system. Report the break-in attempt to your local system administrator or your Internet service provider.

@Java applets are also incapable of searching through your system's memory to obtain information. The Java language itself doesn't have access to random memory locations in your system, which is a method some criminals use to steal passwords and other confidential information.

Notable Java Applets

The following are just a couple of the most notable Java applets on the Web. They're both great examples of what is possible with Java.

The Impressionist, by Paul Haeberli of Silicon Graphics, is one of the most remarkable applets available (see fig. 26.12). It applies Haeberli's patented computer painting techniques to allow you to draw in the style of an impressionist painter. You select one of the nine pictures available on the page or use one of your own, and start with a blank canvas. As you move your mouse pointer over the canvas, the picture is drawn in the impressionist style. The Impressionist is available from

http://reality.sgi.com/grafica/impression/

Fig. 26.12

The Impressionist.

BulletProof has created the first site on the Internet that uses Java to display stock quotes and stock histories (see fig. 26.13). This subscription service allows you to keep your stock portfolio up to date and to search thousands of different securities. Look for it at

http://www.bulletproof.com/WallStreetWeb/

Fig. 26.13

The WallStreetWeb Java applet by BulletProof.

Java and JavaScript Resources

Creating Java applets and JavaScript programs can be a bit difficult, especially for the novice programmer. If you're interested in writing Java applets or JavaScript programs, there are a number of development tools and informational resources available to you.

Development Tools

Since Sun's announcement, many companies have licensed Java and have created Java development tools. Some free development tools are also available. Here are a few:

Symantec (http://www.symantec.com/) has created an integrated development environment (IDE) for @Java called @Symantec Cafe. @Symantec Cafe is available for @Windows 95, @Windows NT, and @Power Macintosh. You can read more about it at

http://www.symantec.com/lit/dev/javaindex.html

Borland International (http://www.borland.com/) has a new debugger for @Java. This @graphical debugger is available on the @Windows 95, @Windows NT, and @Solaris platforms.

Silicon Graphics (http://www.sgi.com) has ported @Java to their @IRIX operating system and has created a development environment called @Cosmo Code. @Cosmo Code provides an extensive set of @utilities for @Java programming, including a source-level debugger. It is available only for Silicon Graphics machines.

Javamaker is a free IDE from Korea. It contains an editor and has buttons to compile your Java programs automatically. It's simple but very effective. Javamaker is available from

http://net.info.samsung.co.kr/~hcchoi/javamaker.html

Diva, another IDE available on the @Internet is a more sophisticated utility than Javamaker. It provides graphical class representations, the ability to write HTML documents, an integrated editor and more. It is available from

http://www.inch.com/~friskel/

Web Resources

Javasoft has a special @WWW site set up especially for @Java (see fig. 26.14). You can reach it at http://www.javasoft.com/. You can find the latest version of the HotJava browser and the Java Development Kit (JDK) at http://www.javasoft.com/download.html.

The Java web site has a "What's @New" page that's updated frequently with news from Sun. It can be accessed from the Java home page or from: http://www.javasoft.com/new.html

The Gamelan home page (http://www.gamelan.com) keeps an extensive list of @Java applets and other @Java resources.

Fig. 26.14

The Java Home page.

You can learn more about JavaScript by going to Netscape's Authoring Guide page:

http://home.netscape.com/comprod/products/navigator/version_2.0/script/script_info/index.html

The JavaScript Index (http://www.c2.org/~andreww/javascript/) contains a list of @JavaScript links with many examples.

Internet Newsgroups and Mailing Lists

The @Internet newsgroups for @Java are shown in table 26.2.

Table 26.2 Internet Java newsgroups.

Group Purpose
comp.lang.java General Java language discussions
comp.lang.javascript General JavaScript discussions
alt.www.hotjava HotJava browser discussions

Reading these @newsgroups is a great way to keep up to date with the most current @Java information, and a great way to meet other people who are also interested in @Java.

Many mailing lists also support Java. Sun maintains several of these Java mailing lists. You should be aware that some of these mailing lists have a tremendous amount of traffic, so be prepared to receive a lot of e-mail if you subscribe to them.

The @java-announce list, a moderated mailing list, distributes press releases and announces new @software releases. Subscribe to this mailing list by sending e-mail with the word Subscribe in the message to

java-announce-request@java.sun.com

The @java-porting list discusses porting @Java to different platforms. If you're interested in porting Java to a new architecture, this is the list for you. Subscribe to this mailing list by sending e-mail with the word Subscribe in the message to

java-porting-request@java.sun.com

The @java-interest list is an unmoderated forum for discussing @Java programming issues that aren't covered by the other lists. The traffic on this list is also sent to comp.lang.java. If you already read that newsgroup, you don't need to subscribe to this list. Subscribe to this mailing list by sending e-mail with the word Subscribe in the message to

java-interest-request@java.sun.com


Internet & New Technologies Home Page - Que Home Page
For technical support for our books and software contact support@mcp.com
© 1996, Que Corporation