Chapter 36

Including Java Applets in Your Web Pages

by Rick Darnell


CONTENTS

Java is one of the hottest topics on the World Wide Web-and for good reason. It offers expanded portability for Web content, including sound and animation, without the use of plug-ins or other helper applications and independent of host hardware. In this sense, Java has helped promote a change in the way page developers think about content on the World Wide Web, similar to the way the World Wide Web changed the way people think about the Internet.

Getting to Know Java

Java is an object-oriented programming language developed by Sun Microsystems, Inc. Although not initially conceived as a way to expand the interactivity and capability of Web pages, it didn't take long for people to see how the platform-independent nature of Java made an ideal fit with the nature of the Internet.

In the past, when an author developed a page with special content beyond the constraints of HTML, an important decision had to be made: either use helper applications or shift the necessary processing to the server. The first solution meant that some content would be inaccessible to some users if they didn't have the helper application or if a helper was unavailable for their system. The second solution meant excluding some content because inherently slow modem lines made animation and sounds unworkable over normal network connections.

Enter Sun's Java. By utilizing a key feature of Java-platform independence-Java applets can implement sound, animation, spreadsheets, e-mail applications, guest books, and virtually anything else you can program, regardless of platform.

Java Safety

Running in a distributed environment, such as an intranet or the World Wide Web, requires safeguards for client computers; a potentially hostile piece of code can do a great deal of damage by erasing files, by formatting disks, and creating other types of damage. Given the way applets are implemented-automatic load and run-you need to ensure the integrity of any piece of code distributed to a broad and uncontrolled audience.

As a Web-page author using Java, you are responsible for ensuring that your applets are clean. The best way is to get them only from trusted sites. Be careful about picking up applets anywhere you find them-the hard drive you save may be your own.

Programmers Love a Challenge
Java is not bulletproof, however. As quick as it was proclaimed "secure," a dedicated group of programmers went to work to find security holes. And they found them. Through cooperative efforts between Sun, Netscape, Microsoft and others, these are getting corrected, but it's still a dangerous world. There are reports of "black Java" applets which are hostile enough to format system drives and pass secure information across the Internet.
There are a few things you can do to protect yourself and your system:
  • Use only the most up-to-date versions of software.
  • If your system enables screening applets at the firewall, take advantage of it. If there are applets you'd like to use, make them available internally.
  • Don't browse a Java site unless you know it's clean.
  • As discussed in the introduction, the compiled bytecode is checked extensively for illegal operations and is verified again on the host system before the applet is run. Although these security features limit the scope and capabilities of an applet, they also help ensure against "Trojan horse" viruses and other shenanigans by less-than-scrupulous programmers.
  • With all of the security features built in, you don't want to implement word processors, spreadsheets, or other interactive applications in Java applets. If you require these programs, consider building a full Java application, which does not contain the security restrictions of an applet.

Although no system can guarantee 100-percent security, Java goes a long way to ensure the protection of client systems from its applets. It uses three security procedures to make the end user safe from malicious attacks:

Bytecode Verification

After a piece of Java code is loaded into memory, it enters the interpreter, where it gets checked for language compliance before the first statement is executed. This process ensures against corruption or changes to the compiled code between compile time and run time.

Memory Layout

Next, the memory layout is determined for each of the classes, preventing would-be hackers from forging access by deducing anything about the structure of a class or the machine it's running on. Memory allocation is different for each class, depending on its structure and the host machine.

File Access Restrictions

After that, the interpreter security continues to monitor the activity of the applet to make sure it doesn't access the host file system, except as specifically allowed by the client or user. You can extend some implementations of this specific feature to include no file access, period.

Platform Independence

This feature is probably the most important one. One compiled piece of Java code can run on any platform with a Java compiler. Currently, the list of platforms includes Windows 95, Solaris, and Macintosh, but there are people hard at work to expand the possibilities. By its very nature, Java does not contain any implementation-specific syntax. This format means a byte is an 8-bit integer and a float is a 32-bit IEEE 754 floating point number, no matter where the applet runs.

And, with object-oriented code, Java takes advantage of a special programming feature that enables programmers to upgrade capabilities simply by adding a new class. When an applet is upgraded, it is not always necessary to reload the entire applet. A small additional class may be all that's needed.

HotJava

HotJava (see Figure 36.1) represents one of the first applications written entirely in Java. In its initial release, HotJava primarily showed how applets could be included as part of an HTML document. Now, it functions closer to a full-featured browser, supporting all of HTML 1 and 2 specifications. Support for HTML 3.2 is also in the process of integration.

Figure 36.1 : The HotJava browser is one of the first stand-alone applications written entirely in the Java language.

Tip
To download a copy of HotJava, point your browser to http://java.sun.com/java.sun.com/hotjava.html. The file size is approximately 3 M.

HotJava operates differently from most browsers in its basic functioning. Settings, preferences, and other basic maintenance screens get stored in the form of HTML documents and classes.

Stripped down to its most basic level, HotJava knows nothing about anything. Classes are added to the browser so it can understand HTML, e-mail, sound files, and other specialty items. As new content and new formats are developed for Web pages, Java will require only the addition of another class. You won't need a complete upgrade to a new version to take advantage of the latest developments.

The Truth About Java-Powered Pages

When Java was first released in 1995, if you wanted to do something nifty on your Web page with an applet, there were two things you needed:

  1. Enough programming language to learn Java.
  2. Users with the HotJava browser to view your applet, because it wasn't yet supported by Netscape or Microsoft.

Fortunately, this situation didn't last very long. Enough programmers and Web developers became interested in Java and before long, a whole bunch of applets were available. Second, Netscape adopted Java compatibility for their 2.0 release of Navigator. This was followed closely by Microsoft, who included Java as part of their 3.0 release of Internet Explorer.

Note
If you're still interested in writing your own applets, the basics are covered in Chapter 37, "Writing Java Applets." For a detailed programming tutorial, check out Teach Yourself Java in 21 Days, available from Sams.net.

HotJava is still available, but it remains a distant choice in the browser market. Although easily customized using Java classes, it's still pretty slow. Sun is not attempting to have it compete with the Big Two, and instead is focusing on intranet and custom markets.

With plenty of applets and Java-compatible browsers, a Java-powered page is as simple as including an applet definition within your HTML document. To wave the Java banner, many page authors also include the Java-Powered icon (see Figure 36.2) as part of the page with the applet or links to other Java pages.

Figure 36.2 : The Java-Powered icon is used by many developers to indicate a page with Java applets.

Why Is Everyone So Hyped About Java?

Java holds a great deal of promise for the World Wide Web and computers in general because it provides a solution to the problem of incompatible platforms. Internets and intranets are no longer expected to include similar or directly compatible machines (all UNIX, all Macintosh, or all pc). Because it has a neutral architecture, the same application written in Java can be used by anyone on the network, without concern for which kind of machine the developer used.

For standalone applications, Java's object-oriented structure gives an easy method to upgrade. The class for the upgrade or extension of the application is downloaded into the appropriate class library; then you can run the updated features.

With its modeling capabilities, Java represents a good choice for implementing advanced Web capabilities and content, such as virtual-reality sites or Web crawlers powered by intelligent agents.

How to Use Java Now

The simplest way to implement Java is through embedding applets in your HTML pages. A wide variety of applets are already available for inclusion, including the animation applet included with the Java Development Kit and a plethora of ticker display applets, which scroll a message or graphic in a half million different ways across the applet frame. An example of a ticker applet is included later in this chapter in the section "Applets for Fun and Utility."

Note
Although spreading quickly, Java applets do not come with all browsers. Netscape Navigator 2.0 and later, Microsoft Internet Explorer 3.0 and later, and Sun's HotJava support Java applets. ncSA Mosaic has included Java compatibility in its wish list for future upgrades to its product, but no word has been given on when that might happen. If your browser is not Java-compatible, the applet section of the HTML page is ignored.

How Applets and Applications Are Different

Java applications work similarly to standalone programs, such as your browser or word processor. They don't require a third-party intermediary, such as HotJava or the applet viewer. Applets require a Java-compatible browser or the appletviewer for viewing. They operate similarly to other objects embedded in HTML documents, such as Shockwave or RealAudio files, which require assistance to run.

Note
The HotJava browser developed by Sun is a Java application that was written and implemented entirely in the Java language.

The fact that applets run on a host system makes them especially suspect and leads to several key security restrictions. Applets have limited capability to interact with their host platform. An applet cannot write files or send files to a printer on the local system. In addition, it cannot read local files or run local applications. Although no system is 100 percent secure, Java goes to great lengths to ensure the integrity of applets generated under its banner.

Java Applets and javascript
It has been said a million times, but if you have just started using Java, it bears repeating: Java isn't JavaScript. JavaScript isn't Java.
Java, in applet or application form, is a compiled language with classes and inheritance. HTML pages can include a reference to Java applets, which then get downloaded and run when a compatible browser finds the tag.
JavaScript is an object-based, client-side scripting language developed by Netscape, but it does not include classes or inheritance. JavaScript exists on the HTML page and gets interpreted by a compatible browser along with the rest of the page.
Although they share some common syntax and terminology, the two items work differently and have different uses. Confusing Java and JavaScript only leads to a steeper learning curve.

Using an Applet on a Web Page

Using applets on a Web page requires a two-part process. First, you must make sure your classes and related files, such as images and audio clips, appear in a directory accessible to the HTML page. One common location is in a classes subdirectory of the HTML documents. Second, the <APPLET> tag that refers to the class is inserted in the Web page, along with any parameters the applet needs to function.

All About the <APPLET> Tag

The <APPLET> tag is used to insert the applet on a page, and it takes the following syntax:


<APPLET CODE="appletName.class" [CODEBASE="pathToClass "] 

WIDTH=xxx HEIGHT=xxx [ALIGN= ][HSPACE= ][VSPACE= ]>

[<PARAMETER name=parameterNamevalue=parameterValue>]

</APPLET>

Although it looks like a lot of options, they're actually pretty simple to understand:

Most applets also require a set of parameters to control their actions. You'll want to check any documentation supplied with the applet to see what's available. There is no limit to the number of parameters you can include within an applet tag. The only rule is that each parameter must appear in a separate <PARAM> tag.

Passing Parameters to Applets

Parameters are used to pass information to an applet so the applet knows about the environment it's in and how it should behave. Some applets have one method of running and don't accept any parameters. Most, however, contain some user-definable parameters that can be changed.

The <PARAM> tag enables you to pass information to the applet. The syntax is this:


<PARAM NAME=paramName VALUE=paramValue>

The parameter name is case-sensitive and must exactly match the parameter name in the applet. If the applet does not provide exceptions for mismatched data types, an incompatible value could cause it not to function. For example, if a parameter calls for an integer and you provide a string, the applet could fail to operate when it attempts to put the string into an integer variable.

There is a small complexity to all of this. You'll notice that some HTML editors that support Java applets include all parameters as strings. The following example passes an integer to the applet as a string:


<PARAM NAME="Pause" VALUE="100">

What gives? The nuance is that all parameters are sent to the applet as strings, regardless of how you represent them in the parameter tag. The conversion to the appropriate data type happens inside the applet. The moral to this story is to make sure the value you send will convert to the right type. If the "Pause" parameter used in the last example wants an integer, don't send it a string.

The <APPLET> Tag and Non-Java Browsers

There is an additional item you can include within an applet tag that you're probably already familiar with-an <IMG> tag. An image tag within an applet is used with browsers that don't support Java.

When interpreting an HTML document, an incompatible browser ignores any tags it doesn't understand. In this case, that includes the applet and parameter tags. However, it ignores them one at a time instead of finding the closing applet tag and ignoring everything in between. When it reaches the <IMG> tag within your applet definition, it knows what to do and loads the image (see Figure 36.3).

Figure 36.3 : Even though ncSA Mosaic is not compatible with Java, it can still display a graphic defined with an <IMG> tag embedded within the <APPLET>.

Here are some tips to help you use this trick effectively:

Tip
Make sure the actual size of your image matches the dimensions of the applet. If the size defined in the image tag is different from the actual size, it could be distorted on the viewer's screen.

This is an easy way to substitute content for users who don't have Java-compatible browsers. Although all of the benefits of Java are lost, there is at least something for them to view, even if it's a message that they should get a Java browser.

Applets for Fun and Utility

This section provides help on using a selection of applets available on the CD-ROM. These applets are free for you to use on your own Web pages.

Animator

Probably one of the most frequently used, the Java animator applet (see Figure 36.4) comes with the Java Developer's Kit and provides a quick-and-easy way to add animation to your Java-powered page.

Figure 36.4 : The Animator applet is used to display a series of images with an option for frame-specific sounds and soundtracks.

Animator also supports synchronized sound with the animation, but the sound must use the Sun .au format. No other sound formats are supported yet. Implementing the applet requires a set of .gif or .jpg files containing the images that form the animation.

Tip
Try to keep the size of the images as small as possible. Each image has to get downloaded to the client machine, adding significantly to the time required for the applet to load and run.

A wide variety of parameters exist, and they control the operation of Animator. Here's the breakdown and syntax:

<APPLET CODE="Animator.class" WIDTH=number HEIGHT=number>  Width should be at least the width in pixels of the widest frame, whereas height should reflect the size of the tallest frame. Smaller values will result in the image getting clipped.
<PARAM NAME=IMAGESOURCE VALUE="pathInfo">  Points to the directory that contains the animation frames. The default directory is the same as the HTML document. By default, the files get named T1.gif, T2.gif, and so on.
<PARAM NAME=STARTUP VALUE="filename">  An image that gets displayed while the applet loads and prepares to run.
<PARAM NAME=BACKGROUND VALUE="filename">  An image file for use as a background for the animation.
<PARAM NAME=BACKGROUNDCOLOR VALUE="color,color,color">  The color for the animation background, represented as an RGB value with a number from 0 to 255 for each of the settings.
<PARAM NAME=STARTIMAGE VALUE=number>  The first frame in the animation (by default 1).
<PARAM NAME=ENDIMAGE VALUE=number>  The last frame in the animation.
<PARAM NAME="NAMEPATTERN" VALUE="dir/prefix%N.suffix">  A pattern to use for generating names based on the STARTIMAGE, ENDIMAGE, and IMAGESOURCE parameters.
<PARAM NAME="PAUSE" VALUE=number>  Number of milliseconds to pause between images (default)-can be overridden by PAUSES.
<PARAM NAME="PAUSES" VALUE="number|number|...">  Millisecond delay per frame, with each value separated by a vertical bar. Blank uses a default PAUSE value.
<PARAM NAME="REPEAT" VALUE=true>  If true, the animation will continue as a loop.
<PARAM NAME="POSITIONS" VALUE="x@y|x@y...">  Screen positions (x@y) for each frame, represented in pixels and separated by vertical bars. A blank value will use the previous frame's position.
<PARAM NAME="IMAGES" VALUE="number|number|...">  Used to define an explicit order for frames, which becomes useful if your frames are out of order or if you want to reverse the sequence (such as "1|2|3|2|1").
<PARAM NAME="SOUNDSOURCE" VALUE="aDirectory">  Indicates the directory with the audio files. The default is the same directory as the class.
<PARAM NAME="SOUNDTRACK" VALUE="aFile">  An audio file to play throughout the animation as background music.
<PARAM NAME="SOUNDS" VALUE="aFile.au|||||bFile.au">  Plays audio files keyed to individual frames.
<PARAM NAME="HREF" VALUE="aURL">  The URL of the page to visit when user clicks the animation (if not set, a mouse click pauses/resumes the animation).

Clock

This applet displays an analog clock onscreen (see Figure 36.5), complete with a sweeping second hand. Right now, no way exists to control the appearance of the clock. It would, however, be a relatively simple matter to add a parameter to control the size of the clock and whether the second hand appears, and to display of the date and time underneath.

Figure 36.5: The Clock applet, a small and simple local-time clock to include on a Web page.

The time gets determined by the host machine. A computer implementation of an analog clock occupies little computer space-just more than 3 K.


<applet code="Clock2.class" width=170 height=150>

</applet>

Nervous Text

Nervous text (see Figure 36.6) works by combining the basic HTML heading with a dose of really strong coffee and a slab of double chocolate cake. The letters jitter and jump around like Mexican jumping beans on a hot pan.

Figure 36.6: The Nervous Text applet moves each letter around in a frantic, haphazard fashion.

Nervous text takes a string of text as its lone parameter. If not included, the default text is HotJava. You can also modify the applet's source code to achieve more flexibility, including controlling the size and color of the font.


<PARAM NAME=text VALUE="string">

Ticker

(http://www.uni-kassel.de/fb16/ipm/mt/java/ticker.htm)

This applet (see Figure 36.7) provides one example of the many "ticker tape" applets available. It is one of the improved versions, having made the extra effort to reduce flicker and provide additional control over the text.

Figure 36.7: The Ticker applet provides a flexible way to display scrolling messages on the browser screen.

It takes a variety of parameters, described here:

<PARAM NAME=msg VALUE="string">  The message to display.
<PARAM NAME=speed VALUE=number>  The animation speed, expressed as the number of pixels per 100 milliseconds. The default is 10.
<PARAM NAME=txtco VALUE="r,g,b">  The color of the message, expressed as an RGB value with numbers from 0 to 255. If omitted, the default is black.
<PARAM NAME=bgco VALUE="r,g,b">  The color of the background. If omitted, the default appears as light gray.
<PARAM NAME=shco VALUE="r,g,b">  The color of the message shadow. If omitted, no shadow appears.
<PARAM NAME=href VALUE="URL">  The ticker can also serve as a hyperlink if the user clicks on the ticker. Either a relative or complete URL is legal.
<PARAM NAME=hrefco VALUE="r,g,b">  The color of the URL frame. If omitted, the default is blue.
<PARAM NAME=start VALUE="yy, mm, dd">/<PARAM NAME=exp VALUE="yy, mm, dd">  Dates to start and stop (expire) displaying the applet. If the page gets viewed outside of these dates, as determined by the host machine, the ticker will not display its message. It will still occupy space on the screen, however. You can use either date parameter by itself.
<PARAM NAME=exfill VALUE="r,g,b">  If the local date falls outside of the start and stop parameters, then the box becomes filled with this color.

Nuclear Power Plant

This little simulation (see Figure 36.8) really doesn't seem useful, unless you plan to run power plants in Russia. It does, however, show a good example of a user interface, object interaction, and animation. After the applet is initialized, you can select one of three powerplant crises-from pump failures to blown turbines. To prevent a meltdown, open and close valves and start pumps as necessary. If you don't work quick enough, the core turns to mush and releases enough radioactivity to ruin everyone's day.

Figure 36.8: The Nuclear Power Plant applet, a creative use of Java as a learning tool and game implementation.

Applet Sources on the Web

Many sources exist for applets on the Web that you can use. Make sure to check the licensing on the applet. Just because an applet appears on a page doesn't mean you can freely use it.

JavaSoft

(http://java.sun.com/)

JavaSoft, a subsidiary of Sun Microsystems, handles the Java products. Go to their Web site (see Figure 36.9) first when looking for information, documentation, updates, downloads, and other feedback. Originally part of the Sun Web site, JavaSoft received its own space to handle the dramatic increase in attention Java has enjoyed since its release.

Figure 36.9: The JavaSoft home page includes links to the Java Developer's Kit, HotJava, and other information of use to Java users and developers.

JavaWorld

(http://www.javaworld.com/)

The first online publication devoted entirely to Java, JavaWorld (see Figure 36.10) comes out monthly and includes news and views about Java developments, along with hands-on tips and tricks. Programming contests are a regular feature, and many articles include links to Java-powered sites, source code, and other helpful items.

Figure 36.10: Java World includes interviews with the movers and shakers in the Java realm, along with hands-on examples, tutorials, and contests.

Gamelan

(http://www.gamelan.com/)

This site was developed specifically for the development and advancement of Java. As such, it shows you what the rest of the world is doing with Java. Links appear here to some of the best applets to date for the viewing, and you can download some for use on your pages (see Figure 36.11). It also includes a page devoted to JavaScript for links devoted to pages utilizing Java's cousin. Some of the innovative productions found here include animators, tickers, network utilities, and a Learn to Dance applet.

Figure 36.11: Gamelan maintains a comprehensive list of links to applications and applets available on the Web.

Summary

Java use keeps spreading quickly as more and more hardware and software manufacturers pledge support to the language and concepts. Even if you never have the chance to delve deep into the intricacies of building an applet or application from scratch, understanding the basics will help you take full advantage of the powerful capabilities available.

Your introduction to the basics of Java continues in the next chapter. You've looked hard at applets from the outside in this chapter; it's time to see what's on the inside. The next chapter gives an introduction to how an applet is constructed, including defining and creating objects and starting and stopping applet operation.