Search This Blog

Sunday, 19 June 2011

What is an Applet ??

What is an Applet ??

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document. After an applet arrives on the client, it has limited access to resources so that it can produce a graphical user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

Two Types of Applets :-
It is important to state at the outset that there are two varieties of applets. The first are those based directly on the Applet class described in this chapter. These applets use the Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no GUI at all). This style of applet has been available since Java was first created.

The second type of applets are those based on the Swing class JApplet. Swing applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user interface than does the AWT. Thus, Swing-based applets are now the most popular.

However, traditional AWT-based applets are still used, especially when only a very simple user interface is required.Thus, both AWT- and Swing-based applets are valid. Because JApplet inherits Applet, all the features of Applet are also available in JApplet

(Note : I will only discuss AWT-Based applets here.)


To use an applet, it is specified in an HTMLfile. One way to do this is by using the APPLET tag. (The OBJECT tag can also be used, but Sun currently recommends the APPLET tag). The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTMLfile.
For example:

<applet code="MyApplet.class" width=200 height=60>

This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high.

Full Syntax of APPLET Tag :-

The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are

[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]

Let’s take a look at each part now.

CODEBASE : CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on the host from which the HTML document was read.

CODE : CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file. This file is relative to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set.

ALT : The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the APPLET tag but can’t currently run Java applets. This is distinct from the alternate HTML you provide for browsers that don’t support applets.

NAME : NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface.

WIDTH and HEIGHT : WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.

ALIGN : ALIGN is an optional attribute that specifies the alignment of the applet. This attribute is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

VSPACE and HSPACE : These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet. They’re treated the same as the IMG tag’s VSPACE and HSPACE attributes.

PARAM NAME and VALUE : The PARAM tag allows you to specify applet-specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

Applet Architecture :-
An applet is a window-based program. As such, its architecture is different from the console-based
programs. If you are familiar withWindows programming, you will be right at home writing applets. If not, then there are a few key concepts you must understand.

First, applets are event driven. An applet resembles a set of interrupt serviceroutines. Here is how the process works. An applet waits until an event occurs. The run-time system notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return. This is a crucial point. For the most part, your applet should not enter a “mode” of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the run-time system. In those situations in which your applet needs to perform a repetitive task on its own (for example,
displaying a scrolling message across its window), you must start an additional thread of execution.

Second, the user initiates interaction with an applet—not the other way around. As you know, in a nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. When the user interacts with one of the controls(buttons,checkboxes,radiobuttons,etc.), an event is generated. While the architecture of an applet is not as easy to understand as that of a console-based program, Java makes it as simple as possible.

An Applet Skeleton (of AWT-based applets) :-
All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them.

AWT-based applets will also override the paint( ) method, which is defined by the AWT Component class. This method is called when the applet’s output must be redisplayed.

(Note : Swing-based applets use a different mechanism to accomplish this task.).

The five methods can be assembled into the skeleton shown here:

// An Applet skeleton of AWT-based applets
import java.awt.*;
import java.applet.*;
<applet code="AppletSkel.class" width=300 height=100>
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization

/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution

// Called when the applet is stopped.
public void stop() {
// suspends execution

/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities

// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window

Applet Initialization and Termination :-
It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the following methods are called, in this sequence:

1. init( )
2. start( )
3. paint( )

When an applet is terminated, the following sequence of method calls takes place:

1. stop( )
2. destroy( )

Let’s look more closely at these methods.

init( )
The init( ) method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

paint( )
The paint( ) method is called each time your applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.

destroy( )
The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

Overriding update( )
In some situations, your applet may need to override another method defined by the AWT, called update( ). This method is called when your applet has requested that a portion of its window be redrawn. The default version of update( ) simply calls paint( ). However, you can override the update( ) method so that it performs more subtle repainting. In general, overriding update( ) is a specialized technique that is not applicable to all applets.

How to Compile and Execute an Applet ?
1) To compile and execute an applet JDK (Java Development Kit) is required. If you dont have it then Download it from here and install it.

2) Let's take the following example. Java code file where we write the applet code which executes when an applet is started or initiated.

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

// Applet code for the "Hello, world!" example.
// This should be saved in a file named as "".

public class HelloWorld extends Applet {

// This method is mandatory, but can be empty (i.e., have no actual code).
   public void init() { }

  // This method is mandatory, but can be empty.(i.e.,have no actual code).
  public void stop() { }

  // Print a message on the screen (x=20, y=10).
  public void paint(Graphics g) {
    g.drawString("Hello, world!", 20,10);

  // Draws a circle on the screen (x=40, y=30).

3) Save this file with same name of the class. Here the class is HelloWorld. Change the file extension to .java . So,we save this file as . Copy paste this file to the directory " C:\Program Files\Java\jdk1.6.0_21\bin "

4) Now open cmd.exe and type " cd C:\Program Files\Java\jdk1.6.0_21\bin " .

5) Now type " javac " and press ENTER.

6) After compiling you java code for an applet you will see a file HelloWorld.class which will be used in the 'code' attribute of the APPLET tag.

7) Now open new notepad and copy paste the following code:

<H1>A Java applet example</H1>
<P>Here it is: <APPLET code="HelloWorld.class" WIDTH="200" HEIGHT="40">
This is where HelloWorld.class runs.</APPLET></P>

Save this file as HelloWorld.html and also move this file to the same directory " C:\Program Files\Java\jdk1.6.0_21\bin ".

8) Now run this HelloWorld.html file and you will see your applet running.

9) You can also use appletviewer to view your applet running. To do this just open cmd.exe go to the same directory where your HelloWorld is saved ,i.e., " C:\Program Files\Java\jdk1.6.0_21\bin " and then type "appletviewer HelloWorld.html". It will run your applet in an appletviewer.

Advantages :-

  • It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by most web browsers.
  • The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of the Java Runtime Environment (JRE) the client will be forced to wait during the large download.
  • Most web browsers cache applets, so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh).
  • It can move the work from the server to the client, making a web solution more scalable with the number of users/clients.
  • If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions.
  • The applet naturally supports the changing user state, such as figure positions on the chessboard.
  • Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions.
  • An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees.
  • Java applets are fast - and can even have similar performance to native installed software.

Disadvantages :-

  • It requires the Java plug-in.
  • Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plug-in.
  • As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals.
  • Some applets require a specific JRE. This is discouraged.
  • If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete.
  • Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy.
  • Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document.

Security :-

There are two applet types with very different security models: unsigned applets and signed applets

Unsigned Applets :-
Limits on unsigned applets are understood as "draconian",they have no access to the local filesystem and web access limited to the applet download site; there are also many other important restrictions. For instance, they cannot access all system properties, use their own class loader, call native code, execute external commands on a local system or redefine classes belonging to core packages included as part of a Java release. While they can run in a standalone frame, such frame contains a header, indicating that this is an untrusted applet. Successful initial call of the forbidden method does not automatically create a security hole as an access controller checks the entire stack of the calling code to be sure the call is not coming from an improper location.
As with any complex system, multiple security problems have been discovered and fixed since Java was first released. Some of these (like the Calendar serialization security bug) persisted for many years with nobody being aware. However it seems that most (if not all) security holes are closed before they can be exploited on a larger scale.
Some studies mention applets crashing the browser or overusing CPU resources but these are classified as nuisances and not as true security flaws. However, unsigned applets may be involved in combined attacks that exploit a combination of multiple severe configuration errors in other parts of the system. An unsigned applet can also be more dangerous to run directly on the server where it is hosted because while code base allows it to talk with the server, running inside it can bypass the firewall. An applet may also try DoS attacks on the server where it is hosted but usually people who manage the web site also manage the applet, making this unreasonable. Communities may solve this problem via source code review or running applets on a dedicated domain.
The unsigned applet can also try to download malware hosted on originating server. However it could only store such file into temporary folder (as its transient data) and has no means to complete the attack by executing it. There were attempts to use applets for spreading Phoenix and Siberia exploits this way, while these exploits do not use Java internally and were also distributed in several other ways.
As of 1999, no real security breaches involving unsigned applets have ever been publicly reported. Using an up-to-date Web browser is usually enough to be safe against the known direct attacks from unsigned applets.

Signed Applets :-
A signed applet contains a signature that the browser should verify through a remotely running, independent certificate authority server. Producing this signature involves specialized tools and interaction with the authority server maintainers. Once the signature is verified, and the user of the current machine also approves, a signed applet can get more rights, becoming equivalent to an ordinary standalone program. The rationale is that the author of the applet is now known and will be responsible for any deliberate damage. This approach allows applets to be used for many tasks that are otherwise not possible by client-side scripting. However, this approach requires more responsibility from the user, deciding whom he or she trusts. The related concerns include a non-responsive authority server, wrong evaluation of the signer identity when issuing certificates, and known applet publishers still doing something that the user would not approve of. Hence signed applets that appeared from Java 1.1 may actually have more security concerns.

Self signed :-
Self-signed applets, which are applets signed by the developer themselves, may potentially pose a security risk; java plugins provide a warning when requesting authorization for a self-signed applet, as the function and safety of the applet is guaranteed only by the developer itself, and has not been independently confirmed. Such self-signed certificates are usually only used during development prior to release where third-party confirmation of security is unimportant, but most applet developers will seek third-party signing to ensure that users trust the applet's safety.

Related Posts Plugin for WordPress, Blogger...