Applets are different from applications, but both are Java programs. Learn the differing capabilities and how to write one program that is both an applet and an application.
Many folks new to Java find the distinctions between applets and applications unsettling and more than a little confusing. I have even had programmers learning Java make the case to me that these distinctions and the differing requirements and capabilities between running in a browser and running in a Java Virtual Machine (JVM) belie the write-once-run-anywhere hyperbole about Java. The distinctions, however, are relatively straightforward, and, once they are mastered, a programmer can use a reasonable programming technique discussed in this article to create a Java program that will run in a browser (an applet) or in a JVM (an application).
First, lets define some terms. An applet is a Java program that runs in a browser. Stated more accurately, a browser provides a context for an applet to execute. A context is defined pretty much as the dictionary defines it: the circumstance in which a particular event occurs; the situation. The browser (which is itself a program) can and does invoke methods to initialize, start, stop, and destroy the applet program. How the browser starts the applet program, finds the resources for the program to run, updates and refreshes the program, and finally disposes of the program is discussed in this article.
Ill also cover Java applications and compare them to applets. Java applications are programs that run in the context of a JVM rather than in a browser. The services provided by the JVM are different from those provided by a browser. The capabilities afforded to an application, especially I/O capabilities, are different by design; applications have more control over their life cycles from start to finish. At the end of the article, Ill present a practical design model for real-world Java software and position AS/400e as a Java server.
The Structure of an Applet
Lets look at some code to see how the two types of programs differ in their architecture. Figure 1 shows the skeleton of an applet with the four milestone methods
(init, start, stop, and destroy) of an applets life cycle in place, but with no code in the methods. First, lets look at the init method. The init method is called by the browser that loads the applet. The browser knows to load the applet by way of the applet tag in the HTML document that the browser loaded first (more about that in a moment). The init method contains (as you might expect from its name) initialization code, plus code that you want to run only once for your program. The init method is guaranteed to precede start and runs only once.
The start method runs after the init method and is called by the browser whenever the HTML page is revisited. An example of revisiting a page is pressing the reload or refresh key. When a user loads or reloads a page, the browser calls the start method. Code that you want to run only once for program initialization should definitely not go here. I once wrote a program that added a text box to the applet in the start routine. Each time I refreshed the screen, the program dutifully added the text box again. This was not the behavior that I wanted, but it was the behavior that I specified by putting the add in the start method. It would have been much better to put the add in the init method.
The stop method is called by the browser each time the page is exited. This prevents running applets from continuing to use processor resources when they are not being viewed in the browser. Stop is guaranteed to run prior to the destroy method and runs one last time if the destroy method is called. The stop method is a good place to temporarily release resources to avoid contention.
The destroy method runs just prior to garbage collection (disposing an object) and always follows the stop method. This is the method that should contain final cleanup code. It should release all open resources, finalize any necessary states, and release any connections back to the server that served the applet.
Three other methods are worth mentioning, as they are often used when writing applets: paint, repaint, and update. I didnt show them in Figure 1, but applets that have a dynamic display will use one or more of these three methods to present a customized graphic, such as animation. The paint, repaint, and update methods are defined in the base component class, appropriately called Component, in the java.awt package. The paint method is the fundamental mechanism that Javas Abstract Window Toolkit (AWT) components use to draw themselves on the screen. Most components, like buttons, list boxes, and so forth, handle their own painting, but if you use components that dont know how to draw themselves (e.g., canvas, panel, or applet), then your derivation of that class must define a paint method to draw your desired graphic. You neednt directly call the paint functionJavas AWT task manager automatically invokes paint when the component needs to be redrawn, when the component is first brought on screen, or when the component is reexposed or scrolled. Paint is also called by the update method.
The repaint function, on the other hand, was designed to be directly called. When you invoke repaint, it basically asks the AWT task manager to call the update method on the component as soon as possible. The update method then works with paint to update the appearance of components.
The thing to remember is that, as long as you are using standard graphical components like lists, menus, and text fields, you neednt worry about coding your own paint, repaint, and update methods. But once you require a custom graphical display, you will have to understand and use these three methods.
Running an Applet
How does a browser know to load an applet? There is a tag in HTML called the applet tag. Figure 2 provides the complete syntax of the applet tag at JDK 1.0.2. JDK 1.1.x
adds two new attributes: archive and object. Figure 3 shows how it might look in actual use in an HTML file.
Ill briefly explain the applet tag here. For more information on applet tags and attributes, consult an HTML manual. An applet tag starts with a less-than symbol and the keyword applet (.
Java Applications (No Browser Required)
Now, lets look at a Java application. Remember that a Java application runs in a JVM rather than in a browser. Figure 4 shows an application skeleton. The first line is an import statement. In this case, the program is importing the java.io package, which provides file and stream I/O functionality. The second line declares a class. Following the class variables (only a comment line in this program) is the main method. The main method is unique to applications. A java application does not have the system-defined milestones of init, start, stop, and destroy that an applet does. When you run a Java application, the system implicitly locates and runs the main method. The main method must be preceded with three keywords: public, static, and void. It accepts a single argument that is an array of strings that act as the entry parameters list. In addition to the main method, your program will probably have other methods that do useful tasks.
Applets Compared to Applications
Applets and applications differ in their capabilities and behavior. Applets are well- mannered guests from another system. Applications are resident on the local system and behave as though they are at home. The table in Figure 5 summarizes the differing capabilities and behavior of applets vs. applications.
It is possible to write a Java program that will run as an applet or an application, depending on the calling context (browser or JVM). To do so, you basically write an applet that includes a main method. The main method will provide a place for the applet to start running when it is called as an application; the main method will be ignored if the Java program is run as an applet. This method must create an applet instance and place it within a frame. The main method must invoke the applet life cycle methods (init, start, stop, and destroy) at the appropriate times to simulate a browser context.
Examples of this technique can be found in many of the available books on Java but the one that I recommend is The Java FAQ by Jonni Kanerva published by Addison- Wesley (ISBN 0201634562).
Java Is Stored in Jars
Java programs are often loaded across a network. They can be packaged to make moving them across the network easier and faster. The jar file format (Java is stored in jarsget it?) creates an archive of multiple Java programs that can be moved and stored as a single entity. The jar file format is a general-purpose storage format, based on the well- known PKWARE ZIP file format. Packaging your programs into jar files permits a single movement of a compressed file, rather than multiple movements of uncompressed files. Individual entries in the jar file can also be digitally signed to authenticate their origin.
A jar file is created using the jar utility that came with your JDK 1.1 JVM. Applets created prior to JDK 1.1 can use jar files by adding the archive attribute to their HTML applet tags. The archive attribute is archive=jars/jarfile.jar.
The jar format handles audio and image files as well as class files, works with existing applets, and is itself written in Java. It is the preferred way to package the pieces and resources needed for an applet to run. The syntax for the jar command is shown in Figure 6.
Which Type Is Right for You?
Which type of Java program will you write? Thats a philosophy, an architecture, and a program design question. If you want to let someone else manage much of the user interface services, if you dont want or need your programs to access the executing machines file system, and if you want everything to run from a central code base, then applets may be a good choice. If you require access to local file systems and multiple arbitrary hosts in your network, or if you need to run in batch, then applications are probably the way to go.
Most of the noise so far in Java has been about client applets. Web programming in Java delivers client applets that interact with the user and maybe the host that served them. Applets can be very useful for graphical tasks or for front-end tasks such as a data entry screen. Applets are in wide use today and will most likely be part of any significant Java code portfolio. Applets are the mechanism for extending an existing enterprise application to the Web.
Applications can do heavier lifting than applets. They have access to the local file system and to native code (through the Java Native Interface, or JNI) and can run without a GUI (making them well-suited for unattended tasks like batch execution). Alsoand this is not yet widely appreciatedbecause applications run in a JVM instead of a browser, they can be used to handle larger computing tasks. JVMs run on both client and server machines (a Windows 95 machine is an example of a client machine; AS/400e is an example of a server machine). A JVM running on an AS/400e with 256 MB of memory (or more) and 8 GB of disk (or more) can run a much larger program than a browser running on a Windows 95 machine with 16 MB or 32 MB of memory.
Java and a Realistic Design Model
Most software implementations done in Java will use both applets and applications. Applets will provide access across the network to the functionality contained in the software. Applications will be used for client software where the infrastructure is under control and supports Java application requirements and will be used for the other tiers of an n-tier client/server architecture. Java software will be done as a multiple-tier client/server system (2, 3, or n).
Many people use the term network-centric to describe the architecture of software written using Java. That term probably is better, as it avoids all those tiresome discussions of client/server models.
I think that software written in Java will, over time, arrive at a four-layer (or tier) model. I deliberately avoid the words client and server here to avoid mapping this relatively
simple conceptual architecture onto an existing model, as I feel that this approach is simpler.
There will be a user interface layer. This layer will use Java applets or applications, as stated previously. There will be a request broker layer, whose function is to manage (prioritize, schedule, and monitor) requests from the various users in the network to the various providers in the network. There will be a business rule layer. The business rule layer will contain debits equal credits kinds of logic and will provide business functionality. And, finally, there will be a data layer. The data layer will provide data management and integrity functionality. This model is in use already today and is a straightforward model against which to design software. I feel compelled to acknowledge that, in any real system, a lot of functionality crosses these conceptual, arbitrary layer borders. So let the consultants argue about whether this is a 2-, 3-, or n-tier model. It is an effective software design and implementation model.
In this model, applets are used only at the user interface layer and not for all of that layer. The request broker, business rule, and data layers are all Java applications. These applications are all Java server applications. Based on analysis of the functional content of large software systems, server-side Java will be much larger than client-side Java. It will also encapsulate much more business value.
What About AS/400e?
Where does the AS/400e fit in this brave new Java world? It runs the request broker(s), the business rule layer, and the data layer. It also serves the applets that provide network access through the user interface layer. It can provide local file storage for the clients that use applications for the user interface layer. AS/400e is well-positioned to be a Java server as the business content of Java software continues to increase.
AS/400e has all the components necessary to be a Java server. It has a JVM that is suited to large computing tasks and large numbers of users; it has a range of options for HTTP serving (HTTP or Internet serving is a prerequisite to serving applets); it has good componentry (the AS/400e Toolbox for Java) for providing access to AS/400e resources; it has excellent cooperative development tools (VisualAge for Java for AS/400e or Borland International Inc.s JBuilder); it has good TCP/IP network support; and it has the necessary security tools (e.g., AS/400e object-based security, firewall support, and encryption support for the network).
Reference Kanerva, Jonni. The Java FAQ. Addison-Wesley: ISBN 0201634562
import java.applet.*;
public class AS400Applet extends Applet {
public void init() {
// Code runs here to initialize the applet
}
public void start() {
// Startup Code Goes Here
}
public void stop() {
// Cleanup Code Goes Here
}
public void destroy() {
// Final CleanUp & Unload Code Goes Here
}
// Presumably used from main, even if indirectly
}
Figure 1: The basic applet structure
Figure 2: The syntax of the applet tag at JDK 1.0.2
Figure 3: The applet tag embedded in HTML
import java.io.*;
class myClass {
// class variables
public static void main(String[] args) {
// method variables
// your deathless code
}
}
}
Figure 4: Java application skeleton
Applet Application
Not resident on local system Must be installed on local file system loaded from server at runtime
Loaded by HTML tag Runs explicitly as parameter to JVM invocation Must run within GUI framework or context Can be GUI or non-GUI
public nonMain(double arg){
Has well-defined life cycle milestones Starts at main method (init, start, stop, destroy) Flow of execution partially controlled Flow of execution completely under program by browser control Runs in a sandbox, so it is more secure Security is according to the Java security model
No constructor; use the init Best to provide a constructor; compiler method to initialize provides default constructor if none present Socket connections permitted to host Socket connections permitted to arbitrary that served applet hosts
Cant load native code Access provided to native code Audio interface No audio interface
Figure 5: Applets vs. applications
jar [jar-file] [manifest-file] files ...
Options:
- c create new archive
- t list table of contents for archive
- x extract named (or all) files from archive
- v generate verbose output on standard error
- f specify archive file name
- m include manifest information from specified manifest file
-0 store only; use no ZIP compression
Figure 6: The Jar command
-M Do not create a manifest file for the entries
LATEST COMMENTS
MC Press Online