22
Sun, Dec
3 New Articles

Applets and Applications

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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, let’s 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.

I’ll 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, I’ll present a practical design model for real-world Java software and position AS/400e as a Java server.

The Structure of an Applet

Let’s 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 applet’s life cycle in place, but with no code in the methods. First, let’s 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 didn’t 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 Java’s 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 don’t 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 needn’t directly call the paint function—Java’s 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 needn’t 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.

I’ll 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 (

A greater-than sign ends the applet attri-butes, and the applet tag ends with .

Java Applications (No Browser Required)

Now, let’s 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 jars—get 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? That’s 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 don’t want or need your programs to access the executing machine’s 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). Also—and this is not yet widely appreciated—because 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

CODE=”appletFile”
ALT=”alternateText”
NAME=”appletInstanceName”
WIDTH=”pixels”
HEIGHT=”pixels”
ALIGN=”alignment”
VSPACE=”pixels”
HSPACE=”pixels”>
PARAM NAME=”appletAttribute2” VALUE>
alternatehtml

Figure 2: The syntax of the applet tag at JDK 1.0.2


Very Simple Applet HTML Page

codebase=”c:jdk102javainY2KWhile.class” align=”baseline”
width=”148” height=”60”>Sorry about that


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

Can’t 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
-M Do not create a manifest file for the entries
Figure 6: The Jar command

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: