Novell is now a part of Micro Focus

Anatomy of a Java Applet: Part 1

Articles and Tips: article

STEVEN C. JONES
Senior Research Engineer
Novell Systems Research

01 Aug 1996


This DevNote starts with an overview of Java applets followed by a comparison of applets vs. Java applications. The DevNote then provides details on the Java-specific HTML tags used to embed Java applets within HTML. The java.applet package is detailed, including coverage of the methods related to the life cycle of an applet. A sample HTML document and an embedded applet are constructed to illustrate the concepts. The sample applet illustrates parameter passing. It has a single method that overrides the paint method. We conclude the discussion with a section covering applet security. This is the first article in a series of articles covering the anatomy of Java applets.

RELATED DEVNOTES Jun 96 "Introduction to Java and the Java Infrastructure for NetWare"" Jun 96 "NetWare SDK for the Java Platform"" Jul 96 "Java on NetWare Takes Shape"

Introduction

The incredible momentum enjoyed by the Java programming language can largely be attributed to Java applets. Applets are a special type of Java application; they are embedded within a HyperText Markup Language (HTML) document. Applets provide an ideal way to give life to a web page. Since the HyperText Markup Language is just that-a text markup language, the medium can eventually be limiting-especially to those who have a development background.

This DevNote provides a concise introduction to Java applets. We cover the following topics:

  • Java applet overview

  • Java applets vs. Java applications

  • Java-specific HTML tags

  • The java.applet package

  • Life cycle of a Java applet

  • Applet parameters

  • Applet security

As we proceed through the DevNote, we construct a sample HTML document that contains a small applet that we will also build as we move along. This article assumes that you are somewhat familiar with Java and concepts related to object-oriented programming. It is also assumed that you are familiar with HTML and other technologies related to the Internet and world-wide web.

Java Applet Overview

Java applets like Java programs consist of one or more class definitions. Once compiled, these classes are stored as files with a .class extension and they consist of Java bytecode. Java bytecode is created by a Java-compatible compiler. Unlike Java applications that typically are executed by a Java-compatible interpreter, applets are executed within a Java-enabled web browser such as Netscape Navigator 2.x and later that includes an integrated bytecode interpreter. Applets are embedded within an HTML document via the APPLET tag that references the Java applet's compiled .class file.

Figure 1: Web page with referencing Java .class file.

Although Java applets are a form of a Java application, some important differences must be considered.

Java Applets Versus Java Applications

A significant difference between Java applications and applets is the level of security in applets. Given applets are untrusted-they allow for downloading code from anywhere on the net-they could potentially wreak havoc on local networks and systems unless some security constraints exist. For this reason, browsers supporting applets carefully limit what applets are allowed to do. We cover security in more detail later in the section "Applet Security."

Perhaps the most significant difference between Java applications and Java applets is their life cycle. Java applets do not require a main() method as Java applications do. When you run a Java application, you do so by invoking a Java-compatible interpreter which loads a .class file that contains the main() method. This is where a Java application's life cycle begins.

Since applets are embedded in HTML documents, their life cycle is a bit more complex. The methods relevant to the life cycle of an applet are covered later in the DevNote in the section "Life Cycle of a Java Applet." Understanding applets means understanding how to embed or reference an applet from an HTML document.

HTML Java-Specific Tags

Most of you are likely familiar with the HyperText Markup Language (HTML). HTML uses tags to specify various types of content, including items "embedded" or referenced by a web page. The APPLET tag is used to reference a Java applet, making it part of a web page. When a user selects a page that contains an applet, the bytecode is downloaded from the web server and executed by the browser's integrated bytecode interpreter. The following HTML document illustrates the use of the APPLET tag in its simplest form:

<html<<
<body<<
<APPLET code=<HelloWorld.class< WIDTH=500 HEIGHT=200<<
</APPLET<<
</body<<
</html<<

This HTML document contains an embedded Java applet named "HelloWorld.class" that is 500 pixels wide and 200 pixels in height. The APPLET tag has the following syntax:

<APPLET<
  [CODEBASE = applet-URL]

  CODE = applet-filename

  WIDTH = pixel-width

  HEIGHT = pixel-height

  [ALT = alternate-text]

  [NAME = applet-name]

  [ALIGN = alignment(LEFT | RIGHT | TOP | TEXTTOP 

     | MIDDLE | ABSMIDDLE | BASELINE | BOTTOM | 

     ABSBOTTOM]

  [VSPACE = vertical-pixel width]

  [HSPACEb= horizontal-pixel-space]

>>
[<PARAM NAME = parameter-name VALUE = parameter-value<]<
[<PARAM NAME = parameter-name VALUE = parameter-value<]<
[alternate-html]

</APPLET<<

If a web browser doesn't support Java applets the APPLET tag is simply ignored and any HTML code included in the alternate-html section, if it exists, will be displayed instead. As the above brackets suggest, the only required applet attribute tags are CODE, WIDTH, and HEIGHT. The following provides a summary of how each of these tags can be used:


Attribute Tag
Description

CODE

Thisrequired attribute is the name of the Javaapplet-the name of the .class file createdby a Java-compatible compiler. The filenamemust be relative to the current URL of theHTML file containing the applet unless theCODEBASE attribute is used. In this casethe filename should be specified relativeto the location specified by the CODEBASEattribute.

CODEBASE

Thisis an optional parameter that can be usedto change the base URL. The default baseURL is the directory specified in the URLof the referencing HTML document. This locationcan be specified absolute or relative andneeds to be a directory, not a filename.

WIDTH

Thisattribute is required and is used to specifythe initial width required by the appletin the web browser. Use a number to indicatethe number of pixels required.

HEIGHT

Thisattribute is also required and like width,it is used to specify the initial heightof the applet in pixels.

ALT

TheALT attribute is similar to the alternate-htmlsection. Use this attribute to display HTMLtext in place of the applet in browsers thatDO understand the APPLET tag but DO NOT supportJava.

NAME

TheNAME attribute is used less often; it isuseful when you have two applets on the samepage that need to communicate with each other.Applets that are running at the same timecan look each other up with the getAppletmethod of the AppletContext class.

ALIGN

TheALIGN attribute, also optional, is used toalign applets relative to text in an HTMLdocument. Text can either flow around anapplet or it can be in line with the text.The values LEFT and RIGHT are used to wraptext around the applet. The rest of the values:TOP, MIDDLE, TEXTTOP, ABSMIDDLE, BASELINEBOTTOM, and ABSBOTTOM are used to place appletsin a line of text. These can be useful forsmaller applets.

VSPACE

Thisoptional attribute allows for space to becreated above AND below the applet. It isspecified in pixels.

HSPACE

Thisoptional attribute allows for space to becreated to the left AND to the right of anapplet. It is also specified in pixels.

PARAM NAME

Thisoptional attribute allow for passing namedparameters from HTML documents to applets.You can pass multiple parameters to an applet.Parameters are passed as strings and canbe retrieved with the getParameter method.

The java.applet Package

The package java.applet contains one class, java.applet.Applet, which extends java.awt.Panel, and three interfaces: AppletContext, AppletStub, and AudioClip. The Applet class must be the superclass of any applet. The following figure illustrates the Java class hierarchy where java.applet is located.

Figure 2: Class hierarchy diagram of java.applet package contents.

The java.applet interfaces provide some methods that may prove useful. The AppletContext interface offers some methods useful for getting information about an applet. The AudioClip interface provides a high-level abstraction used for playing sound clips. The AppletStub interface serves as a stub between the applet and the browser that contains the applet. We will use the AppletStub method getParameter later as part of our sample to get the values of parameters stored in our HTML document.

The java.applet.Applet class includes most of the methods you want to be familiar with in order to control the life cycle of an applet. The first step in creating an applet is to subclass java.applet.Applet and override the appropriate methods. The first line of code in our sample applet will be an import statement that can be used to import specific classes or entire packages. Since this an applet, we need to import the java.applet package. We then start our class definition by subclassing java.applet.Applet. Here is the beginning of our applet.

//import the java.applet package

import java.applet.*   

//subclass Applet

 public class HelloWorld extends Applet {}

Life Cycle of a Java Applet

As discussed earlier, perhaps the most significant difference between Java applications and Java applets is their life cycle. Since an applet is running inside a web browser, the events in the web browser need to be considered. For example, how do you as the applet creator deal with a user doing something as trivial as changing to and from different web pages? Fortunately, methods exist for applets that are automatically invoked at various times, allowing for control over various stages in the life of the applet. These methods include: init, start, stop, destroy, and paint. To control the life cycle, you will override one or more of the following methods:

init() Method. The init method is called by the system when an applet is initially loaded. This is a good location for code that performs any activity that needs to be done once at the beginning of the applet's life cycle. This is a good place to create objects, set parameters, configure states, load images, etc.

start()Method. The start method is called by the system after the init method. It is also called each time a user returns to the web page referencing the applet. Unlike the init method, the start method may be called many times during the life of an applet. If you want code to be executed only once, put it in the init method. If you need code to be executed each time a user returns to a page, such as restarting a thread, the start method is the right place for this type of code.

stop() Method. The stop method is called each time the user leaves a web page that references an applet. The stop method, similar to the start method, can be called a number of times during the life of an applet. It's important to note that the default behavior of an applet is to continue running even after the user has moved to another page; thus, the applet will continue to consume system resources. If you would like to halt the execution of an applet or part of its logic, override the stop method. Also, if you are doing animation, playing audio files, performing calculations in a thread etc. you may want to override the stop method. If not, you can likely ignore the stop method.

destroy() method. The destroy method is called by the system when an applet shuts down normally. It is called only once. The stop method is called before the destroy method. This method can also be ignored for most applets; however, if your applet is consuming resources that should be returned, such as a window handle or a thread that your applet has created, this is good place for such code.

paint() Method. The paint method is perhaps the most commonly overridden applet method. Painting can occur many times in the life of an applet. The paint method is called once after init is called and again each time the web browser is activated. For example, if a user selects another application window and then returns to the browser, the system will call the paint method.

The paint method takes an argument, unlike the other previously discussed methods. The argument is an instance of the class Graphics that is part of the package java.awt. Our sample applet will have a single method-it will override the paint method. Since the paint method requires an argument, we want to use another import statement at the beginning of our applet as follows:

import java.awt.Graphics

    or

  import java.awt.*

At the same time we add the beginnings of the first member of our class, the method that overrides the paint method. The sample applet now looks as follows:

//import the java.applet package

import java.applet.*;

//import the awt package

import java.awt.*; 

//subclass applet

public class HelloWorld extends Applet {

//override the paint method

  public void paint(Graphics g) {

  }

}

Let's now add some code that makes our Hello World a bit more interesting. We will use applet parameters to liven up our HelloWorld class.

Applet Parameters

Applet parameters are a useful way to pass information to applets. Similar to command-line arguments, applets can except parameters passed from HTML documents. Applet parameters are embedded inside the APPLET tag via the tag PARAM. The method getParameter is used to access the value of a named parameter passed from an HTML document.

Our sample will have two parameters-the names of two fonts, "Helvetica" and "TimesRoman." Our HTML page now looks like this:

<html<<
<body<<
<APPLET code=<HelloWorld.class< WIDTH=500 HEIGHT=200<<
<PARAM name=<font1< value=<Helvetica<<<
<PARAM name=<font2< value=<TimesRoman<<<
</APPLET<<
</body<<
</html<<

Once the changes are made to the HTML document, we need to add the code that actually does the work to our applet. We start by creating a new instance of a string to be named "fontname1" and we store the value retrieved by the GetParameter method. We then create an instance of a Font object named "f" using the value of the passed parameter now stored in "fontname1." We set up object "g"-the instance of the Graphics class passed in-with a call to the setFont method. Finally, we call the drawString method which writes our message to the screen in the font we passed in as a parameter. Let's repeat some of the code to make use of both parameters. The applet code now looks like this:

//import the java.applet package

import java.applet.*;

//import the awt package

import java.awt.*;

//subclass Applet

public class HelloWorld extends Applet {

//override the paint method

  public void paint(Graphics g) {

//create String obj. populate via getParameter 

  String fontname1 = getParameter("font1");"
//create Font object, set up with value in String

  Font f = new Font(fontname1, Font.BOLD, 18);

//set up Graphics instance with the setFont method

  g.setFont(f);

//use the drawString method to write to the screen

  g.drawString("Hello World in Helvetica 18 pt. Bold" , 25, 50);"
//repeat basically last four lines for 2nd param.

  String fontname2 = getParameter("font2");"
  Font h = new Font(fontname2, Font.ITALIC, 24);

  g.setFont(h);

  g.drawString("Hello World in Times Roman 24 pt. Italic", 25, 100);"
  }

}

Here is a look at how the finished product looks inside Netscape's Navigator 2.01.

Figure 3: Netscape Navigator with applet loaded.

Before leaving a discussion on applets, we need to discuss security-a very important topic since applets are untrusted code.

Applet Security

Considering that Java is a powerful programming language designed to allow for loading code over the network, most of you probably have a very high degree of concern about security. What's to stop a malicious developer from creating a virus-like program? Because of this destructive harmful potential, various restrictions are placed on applets in order to minimize risk. Be aware that restrictions may very from one browser to another.

In general, applets are restricted and cannot:

  • Read or write to the local file system.

  • Remove or delete files from the local file system.

  • Create or rename directories on the local file system.

  • List directory contents or check for the existence of a file.

  • Obtain file attribute information such as size, type modification time etc.

  • Create network connections to computers other than the source of the Applet

  • Listen or connect via ports on the local system.

  • Read from or modify various local system properties.

  • Halt the execution of Java interpreter.

  • Load local libraries or invoke local executables.

Even with such restrictions, the power of the Java language can be abused, allowing for security holes. For example, malicious (or bad) code may inflict a denial of service attack. A denial of service attack is caused by code that stops or significantly degrades the performance of a critical resource.

The idea of certification for applets is being suggested by many in the industry as an answer to attacks such as denial of service.

Security is specific to the browser; some browsers are less constrained than others. Depending on the level of security implemented by the browser, other types of attacks could occur. Overall, the Java language and restrictions placed on applets are sufficient to provide a relatively safe computing environment.

Summary

Java applets are an ideal way to enhance the static world of HTML with a dynamic environment. This DevNote provided an introduction to the anatomy of a Java applet. We described what an applet is and how it is a special case of a Java application. Java applets have a different life cycle and tighter security restrictions. In the interest of space and time, we have not covered all the information related to the java.applet package and applets in general.

If you haven't read the Sun documentation on the java.applet package, you can find it at Sun's web site http://java.sun.com/doc/.

Probably the best way to get familiar with applets is to practice writing them. Look for future DevNotes that cover applets in more detail, including sample code. If you want to get more sample code right away, visit Earthweb's Java Directory at http://www.gamelan.com for plenty of sample code and links other Java-related sites. If you have feedback on this article or suggestions for future DevNotes covering Java applets or Java in general, send E-mail to SCJONES@NOVELL.COM.

For More Information

Please refer to the following Novell Application Notes and Web sites for related Java information:

AppNote February 96 "Exploring the NetWare Web Server"

AppNote March 96 "Exploring the NetWare Web Server: Part 2"

Novell's DeveloperNet web site at URL: http://developer.novell.com/

Novell's Java web site at the URL: http://developer.novell.com/ndk/javaprog.htm

Sun's Java web site at http://java.sun.com/

Earthweb's Java directory at http://www.gamelan.com

* Originally published in Novell AppNotes


Disclaimer

The origin of this information may be internal or external to Novell. While Novell makes all reasonable efforts to verify this information, Novell does not make explicit or implied claims to its validity.

© Copyright Micro Focus or one of its affiliates