Architecture
Analysis
Customer Appraisal
Architecture Framework Assessment
CORBA Architecture
Overview
Microsoft DCOM Architecture
Comparison of Object Frameworks
Assessing CORBA for the Architecture
CORBA Applicability
CORBA Architecture Implementation Considerations
CORBA Implementation Stages
Applet Design
Critical Issues
Applet Design Details
Applet Design Elements
Applet Rules
Tier Two Design Choices
Java Interface Definition Language (IDL) Architecture
Overview Tier Three Design
Architecture
Analysis
Applet
Design Critical Issues
Applet Definition
Applet is a small Java application which runs
within / from a browser in the client tier of the application.
Usually the applet is embedded in the HTML. The
applet HTML tag is looks like
<applet
code = myapplet
width = 200
height = 200
</applet>
Applets can provide user interface, input validation
in the client tier. Applets can communicate with other applets loaded from
the same HTML page.Applets can communicate to a server side component within
its security limitations. Capabilities / advantages of applets
-
Load data files specified relative to the URL
of the applet or the page in which it is running.
-
Display short status strings.
-
Make the browser display a document.
-
Find other applets running in the same page.
-
Play sounds.
-
Get parameters specified by the user in the
<APPLET> tag.
-
Applets can usually make network connections to the
host they came from.
-
Applets running within a Web browser can easily cause
HTML documents to be displayed.
-
Applets can invoke public methods of other applets
on the same page.
-
Although most applets stop running once you
leave their page, they don't have to.
With these capabilities / advantages applets
is a choice for the client tier.
Applet getCodeBase and getDocumentBase
API
A applet is embeded in an HTML page. Two applet
API getCodeBase and getDocumentBase are important.
The URL from where the applet class was loaded
is returned by the getCodeBase. The URL from where the HTML was loaded
is returned by the getDocumentBase.
Importance of the getCodeBase and getDocumentBase
These API are important from the security point
of the applet. When the applets needs to load / access some some file when
the relative url is given for the file location.
Finding and Loading Data Files
Whenever
an applet needs to load some data from a file that's specified with a relative
URL (a URL that doesn't completely specify the file's location), the applet
usually uses either the code base or the document base to form the complete
URL. The code base, returned by the Applet getCodeBase method, is a URL
that specifies the directory from which the applet's classes were loaded.
The document base, returned by the Applet getDocumentBase method, specifies
the directory of the HTML page that contains the applet.
Unless the <APPLET> tag specifies a code base,
both the code base and document base refer to the same directory on the
same server. For example, in the figure in Test Driving an Applet..\overview/test.html..\overview/test.html,
the code and document bases would both specify the someDirectory directory.
Data that the applet always needs, or needs to
rely on as a backup, is usually specified relative to the code base. Data
that the applet user specifies, often by using parameters, is usually specified
relative to the document base.
For security reasons, browsers limit the URLs
from which untrusted applets can read. For example, most browsers don't
allow untrusted applets to use ".." to get to directories above the code
base or document base. Also, since untrusted applets can't read files except
those on the applet's originating host, the document base isn't generally
useful if the document and the untrusted applet are on different servers.
The Applet class defines convenient forms of image-loading
and sound-loading methods that let you specify images and sounds relative
to a base URL. For example, assume an applet is set up with one of the
directory structures shown in the following figure.
To create an Image object using the a.gif image
file under imgDir, the applet can use the following code:
Image image = getImage(getCodeBase(), "imgDir/a.gif");
Sending Messages to Other Applets
Applets can find other applets and send messages
to them, with the following security restrictions:
-
Many browsers require that the applets originate
from the same server.
-
Many browsers further require that the applets
originate from the same directory on the server (the same code base).
-
The Java API requres that the applets be running
on the same page, in the same browser window.
Some browsers let applets invoke methods on
other applets -- even applets on different pages in the same browser --
as long as all of the applets come from the same code base. This method
of interapplet communication isn't supported by the Java API, so it's possible
that it will not be supported by all browsers.
An applet can find another applet either by looking
it up by name (using the AppletContext getApplet method) or by finding
all the applets on the page (using the AppletContext getApplets method).
Both methods, if successful, give the caller one or more Applet objects.
Once the caller finds an Applet object, the caller can invoke methods on
the object.
Finding an Applet by Name: The getApplet Method
The getApplet method looks through all of the
applets on the current page to see if one of them has the specified name.
If so, getApplet returns the applet's Applet object.
By default, an applet has no name. For an applet
to have a name, one must be specified in the HTML code that adds the applet
to a page. You can specify an applet's name in two ways:
By specifying a NAME attribute within the applet's
<APPLET> tag. For example:
<APPLET CODEBASE=example/ CODE=Sender.class
WIDTH=450 HEIGHT=200
NAME="buddy">
. . .
</applet>
? By specifying a NAME parameter with a <PARAM>
tag. For example:
<APPLET CODEBASE=example/ CODE=Receiver.class
WIDTH=450 HEIGHT=35>
<PARAM NAME="name" value="old pal">
. . .
</applet>
Although at least one Java-enabled browser
conducts a case-sensitive search, the expected behavior is for the getApplet
method to perform a case-insensitive search. For example, getApplet("old
pal") and getApplet("OLD PAL") should both find an applet named "Old Pal".
Every applet is implemented by creating a subclass
of the Applet class. The following figure shows the inheritance hierarchy
of the Applet class. This hierarchy determines much of what an applet can
do and how, as you'll see on the next few pages.
What Applets Can and Can't Do
Security Restrictions
Every browser implements security policies to
keep applets from compromising system security. This section describes
the security policies that current browsers adhere to. However, the implementation
of the security policies differs from browser to browser. Also, security
policies are subject to change. For example, if a browser is developed
for use only in trusted environments, then its security policies will likely
be much more lax than those described here.
Current browsers impose the following restrictions
on any applet that is loaded over the network:
-
An applet cannot load libraries or define native
methods.
-
It cannot ordinarily read or write files on
the host that's executing it.
-
It cannot make network connections except to
the host that it came from.
-
It cannot start any program on the host that's
executing it.
-
It cannot read certain system properties.
-
Windows that an applet brings up look different
than windows that an application brings up.
Each browser has a SecurityManager object that implements
its security policies. When a SecurityManager detects a violation, it throws
a SecurityException. Your applet can catch this SecurityException and react
appropriately.
Finding and Loading Data Files
Whenever an applet needs to load some data from
a file that's specified with a relative URL (a URL that doesn't completely
specify the file's location), the applet usually uses either the code base
or the document base to form the complete URL. The code base, returned
by the Applet getCodeBase method, is a URL that specifies the directory
from which the applet's classes were loaded. The document base, returned
by the Applet getDocumentBase method, specifies the directory of the HTML
page that contains the applet.
Unless the <APPLET> tag specifies a code base,
both the code base and document base refer to the same directory on the
same server. For example, in the figure in Test Driving an Applet..\overview/test.html..\overview/test.html,
the code and document bases would both specify the someDirectory directory.
Data that the applet always needs, or needs to
rely on as a backup, is usually specified relative to the code base. Data
that the applet user specifies, often by using parameters, is usually specified
relative to the document base.
For security reasons, browsers limit the URLs
from which untrusted applets can read. For example, most browsers don't
allow untrusted applets to use ".." to get to directories above the code
base or document base. Also, since untrusted applets can't read files except
those on the applet's originating host, the document base isn't generally
useful if the document and the untrusted applet are on different servers.
Practical Considerations when Writing Applets
Security Restrictions
One of the main goals of the Java environment
is to make browser users feel secure running any applet. To achieve this
goal, we've started out conservatively, restricting capabilities perhaps
more than necessary. As time passes, applets will probably get more and
more abilities.
Each applet viewer has a SecurityManager object
that checks for applet security violations. When a SecurityManager detects
a violation, it creates and throws a SecurityException object. Generally,
the SecurityException constructor prints a warning message to the standard
output. An applet can catch SecurityExceptions and react appropriately,
such as by reassuring the user and by resorting to a "safer" (but less
ideal) way of accomplishing the task.
Some applet viewers swallow some SecurityExceptions,
so that the applet never gets the SecurityException. For example, the JDK
Applet Viewer's implementation of the AppletContext getApplet and getApplets
methods simply catches and ignores any SecurityExceptions. The user can
see an error message in the standard output, but at least the applet gets
a valid result from the methods. This makes some sense, since getApplets
should be able to return any valid applets it finds, even if it encounters
invalid ones. (The Applet Viewer considers an applet valid if it's loaded
from the same host as the applet that's calling getApplets.)
Existing applet viewers (including Web browsers)
impose the following restrictions:
Applets cannot load libraries or define native
methods.
Applets can use only their own Java code and
the Java API the applet viewer provides. At a minimum, each applet viewer
must provide access to the API defined in the java.* packages.
An applet cannot ordinarily read or write files
on the host that is executing it.
The JDK Applet Viewer actually permits some user-specified
exceptions to this rule, but Netscape Navigator 2.0, for example, does
not. Applets in any applet viewer can read files specified with full URLs,
instead of by a filename. A workaround for not being to write files is
to have the applet forward data to an application on the host the applet
came from.
An applet cannot make network connections except
to the host that it came from.
The workaround for this restriction is to have
the applet work with an application on the host it came from. The application
can make its own connections anywhere on the network. See Using a Server
to Work Around Security Restrictions for an example.
An applet cannot start any program on the host
that is executing it.
Again, an applet can work with a server-side
application instead.
An applet cannot read certain system properties.
See Reading System Properties for more information.
Windows that an applet brings up look different
than windows that an application brings up.
Applet windows have some warning text and either
a colored bar or an image. This helps the user distinguish applet windows
from those of trusted applications.
The following figures show a window brought up
by a program that can run either as an applet or as an application. The
first figure shows what the window looks like when the program is run as
an application on the Solaris platform. The second figure shows the window
when the program runs as an applet within the Solaris Netscape Navigator
2.0 browser.
Working with a Server-Side Application
Applets, like other Java programs, can use the
API defined in the java.net package to communicate across the network.
The only difference is that, for security reasons, the only host an applet
can communicate with is the host it was delivered from.
Depending on the networking environment an applet
is loaded into, and depending on the browser that runs the applet, an applet
might not be able to communicate with its originating host. For example,
browsers running on hosts inside firewalls often cannot get much information
about the world outside the firewall. As a result, some browsers might
not allow applet communication to hosts outside the firewall.
It's easy to find out which host an applet came
from. Just use the Applet getCodeBase method and the java.net.URL getHost
method, like this:
String host = getCodeBase().getHost();
Once you have the right host name, you can use
all the networking code that is documented in the Custom Networking..\..\networking/index.html..\..\networking/index.html
trail.
3: Design Considerations
When you begin a software project, ask yourself
these three questions:
-
How do I want to deliver my software to users?
-
How can I design an application that is accessible
to all potential users?
-
How can I design an application that suits a global
audience and requires minimal effort to localize?
Choosing an Application or an Applet
At the beginning of the development process,
you must decide if you want to create a standalone application or an applet
that is displayed in a web browser. The following figure shows the different
environments for running applications and applets. ( add fig later )
When deciding between an application and an applet,
the two main issues you need to consider are distribution and security,
including read and write permissions. If you decide to use an applet, you
must also decide whether to display your applet in the user's current browser
window or in a separate browser window.
For an example of an application that uses the
Java look and feel, see MetalEdit Application. For an example of an applet,
see Retirement Savings Calculator Applet. For a list of additional reading
on applets, see Design for Applets.
Distribution
When deciding how to distribute your software,
weigh the needs of both end users and administrators. Don't forget to consider
ease-of-use issues for:
-
Initial distribution and installation of the software
-
Maintenance of the software
-
Updates to the software
-
Daily access to the software
At one extreme is the standalone application, distributed
on a CD-ROM disc or a floppy disk and installed on the end user's local
hard disk. Once the application is installed, users can easily access it.
In an enterprise environment, however, maintenance can be complicated because
separate copies of the application exist on each user's local computer.
Distribution of the original application and subsequent updates require
shipment of the software to, and installation by, multiple users.
In contrast, applets are simpler to distribute
and maintain because they are installed on a central web server. Using
a web browser on their local machines, users can access the latest version
of the applet from anywhere on the intranet or Internet. Users, however,
must download the applet over the network each time they start the applet. If you are creating an applet, make sure that
your users have a browser that contains the JFC or that they are using
JavaTM Plug-In. That way, users will not have to download the JFC every
time they run the applet.
Security Issues
Another issue to consider is whether your software
needs to read and write files. Standalone Java applications can read or
write files on the user's hard disk just as other applications do. For
example, the MetalEdit application reads and writes documents on the user's
local disk.
In contrast, applets usually cannot access a
user's hard disk because they are intended for display on a web page, which
might come from an unknown source. Applets are better suited for tasks
that do not require access to a user's hard disk. For example, a web page
for a bank might offer an applet that calculates home mortgage payments
and prints results, but does not save files on the customer's hard disk.
You can also use applets as a front end to a
central database. For example, the Retirement Savings Calculator applet
enables company employees to select funds for their retirement contribution
and update the amount of their contribution in the company database.
Placement of Applets
If you decide to design an applet, you can display
your applet in the user's current browser window or in a separate browser
window.
Applets in the User's Current Browser Window
The current browser window is well suited for
displaying applets in which users perform a single task. This approach
enables users to perform the task and then resume other activities in the
browser, such as surfing the web.
An applet displayed in the current browser window
should not include a menu bar--having a menu bar in both the applet and
the browser might confuse users. The mnemonics assigned in the applet must
also be different from the mnemonics used to control the browser window;
otherwise, the mnemonics might conflict.
A disadvantage of using the current browser window
is that the applet terminates when users navigate to another web page.
The current settings and data in the applet are lost. To use the applet
again, users must navigate back to the page that contains the applet and
reload the page.
Applets in Separate Browser Windows
If your applet involves more than one task or
if users might visit other web pages before completing the task, launch
a separate browser window and display the applet there. This approach enables
users to interact with the applet and maintain the original browser window
for other activities. Navigating to another web page in the original browser
window does not affect the applet in the separate browser window.
Designing an applet for a separate browser window
is simpler if you remove the browser's normal menu and navigation controls.
Doing so avoids confusion between the browser's menu and controls and the
applet's menus and controls. You also avoid potential conflicts between
mnemonics in the two windows.
CORBA Architecture Overview
Overview of CORBA
The Common Object Request Broker Architecture
(CORBA) is an emerging open distributed object computing infrastructure
being standardized by the Object Management Group. CORBA automates many
common network programming tasks such as object registration, location,
and activation; request demultiplexing; framing and error-handling; parameter
marshalling and demarshalling; and operation dispatching.
The following figure illustrates the primary components
in the OMG Reference Model architecture. Descriptions of these components
are available further below. Portions of these descriptions are based on
material from
Object Services -- These are domain-independent
interfaces that are used by many distributed object programs. For example,
a service providing for the discovery of other available services is almost
always necessary regardless of the application domain. Two examples of
Object Services that fulfill this role are:
-
The Naming Service -- which allows clients to find
objects based on names;
-
The Trading Service -- which allows clients to find
objects based on their properties.
There are also Object Service specifications
for lifecycle management, security, transactions, and event notification,
as well as many others
Common Facilities -- Like Object Service
interfaces, these interfaces are also horizontally-oriented, but unlike
Object Services they are oriented towards end-user applications. An example
of such a facility is the Distributed Document Component Facility (DDCF),
a compound document Common Facility based on OpenDoc. DDCF allows for the
presentation and interchange of objects based on a document model, for
example, facilitating the linking of a spreadsheet object into a report
document.
Domain Interfaces -- These interfaces fill
roles similar to Object Services and Common Facilities but are oriented
towards specific application domains. For example, one of the first OMG
RFPs issued for Domain Interfaces is for Product Data Management (PDM)
Enablers for the manufacturing domain. Other OMG RFPs will soon be issued
in the telecommunications, medical, and financial domains.
Application Interfaces - These are interfaces
developed specifically for a given application. Because they are application-specific,
and because the OMG does not develop applications (only specifications),
these interfaces are not standardized. However, if over time it appears
that certain broadly useful services emerge out of a particular application
domain, they might become candidates for future OMG standardization.
CORBA ORB Architecture
The following figure illustrates the primary
components in the CORBA ORB architecture. Descriptions of these components
are available below the figure.
( Fig CORBA ORB Architecture later
)
Object Implementation -- This defines operations
that implement a CORBA IDL interface. Object implementations can be written
in a variety of languages including C, C++, Java, Smalltalk, and Ada.
Client -- This is the program entity that
invokes an operation on an object implementation. Accessing the services
of a remote object should be transparent to the caller. Ideally, it should
be as simple as calling a method on an object, i.e., obj->op(args). The
remaining components in Figure 2 help to support this level of transparency.
Object Request Broker (ORB) -- The ORB
provides a mechanism for transparently communicating client requests to
target object implementations. The ORB simplifies distributed programming
by decoupling the client from the details of the method invocations. This
makes client requests appear to be local procedure calls. When a client
invokes an operation, the ORB is responsible for finding the object implementation,
transparently activating it if necessary, delivering the request to the
object, and returning any response to the caller.
ORB Interface -- An ORB is a logical entity
that may be implemented in various ways (such as one or more processes
or a set of libraries). To decouple applications from implementation details,
the CORBA specification defines an abstract interface for an ORB. This
interface provides various helper functions such as converting object references
to strings and vice versa, and creating argument lists for requests made
through the dynamic invocation interface described below.
CORBA IDL stubs and skeletons -- CORBA
IDL stubs and skeletons serve as the ``glue'' between the client and server
applications, respectively, and the ORB. The transformation between CORBA
IDL definitions and the target programming language is automated by a CORBA
IDL compiler. The use of a compiler reduces the potential for inconsistencies
between client stubs and server skeletons and increases opportunities for
automated compiler optimizations.
Dynamic Invocation Interface (DII) -- This
interface allows a client to directly access the underlying request mechanisms
provided by an ORB. Applications use the DII to dynamically issue requests
to objects without requiring IDL interface-specific stubs to be linked
in. Unlike IDL stubs (which only allow RPC-style requests), the DII also
allows clients to make non-blocking deferred synchronous (separate send
and receive operations) and oneway (send-only) calls.
Dynamic Skeleton Interface (DSI) -- This
is the server side's analogue to the client side's DII. The DSI allows
an ORB to deliver requests to an object implementation that does not have
compile-time knowledge of the type of the object it is implementing. The
client making the request has no idea whether the implementation is using
the type-specific IDL skeletons or is using the dynamic skeletons.
Object Adapter -- This assists the ORB
with delivering requests to the object and with activating the object.
More importantly, an object adapter associates object implementations with
the ORB. Object adapters can be specialized to provide support for certain
object implementation styles (such as OODB object adapters for persistence
and library object adapters for non-remote objects).
Communication Between Applets and Servlets:
Establishing a Channel
Java applets provide a unique platform for creating
lively applications that are accessible via the browser. While there are
self-contained applets that dazzle Web pages with special effects, most
applets require connectivity to data sources and other applications to
accomplish their tasks. There are, however, inherent architectural and
technical issues for applets that require connectivity to other resources.
For example, the security model used by browsers
to run Java applets restricts their network connections. Another factor
is the inconsistency of JVM implementations in various browsers. There
is also a noticeable delay between the time a new Java version is made
available and its integration in the popular browsers.
Sun has attempted to address these issues by
creating the Java Plug-in. The plug-in is made by Sun and is usually available
shortly after a new version of the JDK is released. The Plug-in replaces
the internal JVM used by the browser. While this approach works in somewhat
controlled environments, it has its own problems when it comes to the huge
Internet audience.
At the very least, in order for this model to
be successful, one has to assume that everyone has installed the latest
version of the Java Plug-in on their machines. Again, while this assumption
may make sense in an intranet environment, it can not be applied to the
broad Internet audience. There is also some slight modifications in the
HTML code containing the Java applet that is needed to take advantage of
the Plug-in environment.
So what we are left with is a good technology
with limitations on its deployment. I have seen my share of projects that
have stalled due to deployment issues of Java applets. The project managers
assumed that by a certain date a particular version of Java would be widely
supported by browsers, and when that assumption failed to materialize,
so did their deployment plans.
Alternative Approaches
Many experts (including those from Sun itself)
indicate that their preference is to use Java on the server and rely on
HTML to create the GUI that is to run on the browser. That approach may
make sense for a number of sites, but there are instances where HTML (or
even DHTML) simply cannot replace the richness and the interactivity that
a live program (i.e., a Java applet) can provide. Applications that rely
on rich presentation slides, real-time graphs and statistics, and sophisticated
user interfaces rely on Java applets. So one approach that has seen success
is not to abandon Java applets altogether, but to limit the functionality
of an applet and rely more on back-end resources.
For example, instead of having the applet perform
time-consuming calculations and then drawing a graph, have a back-end program
do the calculations and then send to the applet just the necessary data
to draw the graph. Of course, this approach requires connectivity between
the applet and server-side programs — which is the topic of this article.
There are a number of mechanisms where applets
and server-side programs like servlets can communicate with each other.
For example, an applet can make RMI calls to server-side processes or use
CORBA to activate remote methods. Architecturally, process separation using
remote objects is an elegant solution, but there are deployment issues
with both CORBA and RMI. Many corporate firewalls block such traffic which
in effect eliminates the above technologies as a communication choice.
Another approach would be to refresh the HTML
page containing the applet and pass new parameters to it. In this scenario,
the server-side process would repaint the entire HTML page at a given time
interval. As part of the repainting, the parameters to the applet are updated.
The applet will then display itself based on the new parameters. This is
a one-way communication channel (the server sends messages to the applet)
and is also very inefficient.
Relying on HTTP
The communication channel between an applet and
a servlet must be simple and deployable in various environments. If you
look at the essence of such communication, it typically involves the applet
initiating a request to the server-side program. This request contains
some data. The server-side program must receive the request, interpret
it and send a response back to the applet. What I have just described is
identical to how a browser communicates with a Web server through HTTP.
Java has built-in support for both HTTP and URL-based connections. So all
we have to do is to open a connection to a servlet specified by an URL
and send data to it. Granted, HTTP is not the most efficient protocol,
but it does provide a channel through which data exchange can be done and
that is what we are after.
Due to the applet security model, there is a
restriction with the above approach. The applet can only communicate back
to the server from which it came from. So wherever our server-side process
is running, that's where the applet must come from. The server-side program
is free to open channels to other resources such as remote databases, CORBA
objects, EJB servers, etc. So from the design perspective, we can still
utilize the benefits that remote objects provide.
The applet must know the URL of the server-side
process. For our purposes, we use a servlet, but CGI scripts, JSP, ASP,
or other server-side processes that can communicate via HTTP can be used.
Once we have the URL, we can open a connection and send data:
String urlAddress = "http://www.someurl.com/someServlet"
java.net.URL url = new java.net.URL(urlAddress);
java.net.URLConnection c = url.openConnection();
This will give us the communication channel to
the servlet. What we have to do next is to send the servlet some data in
the context of a request. We don't want to restrict ourselves to a particular
data type. To facilitate this, we create an output stream and write our
data in terms of bytes to it. Note that an instance of the ByteArrayOutputStream
is used to create the actual DataOutputStream. If you look at the DataOutputStream
class, you'll see a number of "write" methods for various data types. We
use the writeUTF() method to write a simple text message.
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bytesOut);
out.writeUTF("Hello World");
out.flush();
Before sending our message, we need to calculate
its size. To do that, we create an array of bytes that will store our data.
The length of that array is the size of our data. We also need to specify
in our request the MIME type and the length of the request message data.
byte buffer[] = bytesOut.toByteArray();
c.setRequestProperty("Content-type","application/octet-stream");
c.setRequestProperty("Content-length","" + buffer.length);
Finally, we can create a new DataOutputStream
to write the data to the connection we established earlier. The data we
are writing out is simply the array of bytes we created earlier.
DataOutputStream out2 = new DataOutputStream(c.getOutputStream());
out2.write(buffer)
Architecture Analysis
Taking Advantage of the Applet API
The applet API lets you take advantage of the
close relationship that applets have with Web browsers. The API is provided
by the java.applet package -- mainly by the Applet class and the AppletContext
interface. Thanks to the applet API, applets can do the following:
? Be notified by the browser of milestones.
? Load data files specified relative to the URL
of the applet or the page in which it is running.
? Display short status strings.
? Make the browser display a document.
? Find other applets running in the same page.
? Play sounds.
? Get parameters specified by the user in the
<APPLET> tag.
Finding and Loading Data Files
Whenever an applet needs to load some data from
a file that's specified with a relative URL (a URL that doesn't completely
specify the file's location), the applet usually uses either the code base
or the document base to form the complete URL. The code base, returned
by the Applet getCodeBase method, is a URL that specifies the directory
from which the applet's classes were loaded. The document base, returned
by the Applet getDocumentBase method, specifies the directory of the HTML
page that contains the applet.
Unless the <APPLET> tag specifies a code base,
both the code base and document base refer to the same directory on the
same server. For example, in the figure in Test Driving an Applet..\overview/test.html..\overview/test.html,
the code and document bases would both specify the someDirectory directory.
Data that the applet always needs, or needs to
rely on as a backup, is usually specified relative to the code base. Data
that the applet user specifies, often by using parameters, is usually specified
relative to the document base.
Note: For security reasons, browsers limit the
URLs from which untrusted applets can read. For example, most browsers
don't allow untrusted applets to use ".." to get to directories above the
code base or document base. Also, since untrusted applets can't read files
except those on the applet's originating host, the document base isn't
generally useful if the document and the untrusted applet are on different
servers.
The Applet class defines convenient forms of image-loading
and sound-loading methods that let you specify images and sounds relative
to a base URL. For example, assume an applet is set up with one of the
directory structures shown in the following figure.
[PENDING: Figure. For the no-package case, imgDir
and the class file are in the same directory. For the package case, imgDir
and top package directory (com) are in the same directory.]
To create an Image object using the a.gif image
file under imgDir, the applet can use the following code:
Image image = getImage(getCodeBase(), "imgDir/a.gif");
Sending Messages to Other Applets
Applets can find other applets and send messages
to them, with the following security restrictions:
? Many browsers require that the applets originate
from the same server.
? Many browsers further require that the applets
originate from the same directory on the server (the same code base).
? The Java API requres that the applets be running
on the same page, in the same browser window.
Note: Some browsers let applets invoke methods
on other applets -- even applets on different pages in the same browser
-- as long as all of the applets come from the same code base. This method
of interapplet communication isn't supported by the Java API, so it's possible
that it will not be supported by all browsers.
An applet can find another applet either by looking
it up by name (using the AppletContext getApplet method) or by finding
all the applets on the page (using the AppletContext getApplets method).
Both methods, if successful, give the caller one or more Applet objects.
Once the caller finds an Applet object, the caller can invoke methods on
the object.
Finding an Applet by Name: The getApplet Method
The getApplet method looks through all of the
applets on the current page to see if one of them has the specified name.
If so, getApplet returns the applet's Applet object.
By default, an applet has no name. For an applet
to have a name, one must be specified in the HTML code that adds the applet
to a page. You can specify an applet's name in two ways:
? By specifying a NAME attribute within the applet's
<APPLET> tag. For example:
<APPLET CODEBASE=example/ CODE=Sender.class
WIDTH=450 HEIGHT=200
NAME="buddy">
. . .
</applet>
? By specifying a NAME parameter with a <PARAM>
tag. For example:
<APPLET CODEBASE=example/ CODE=Receiver.class
WIDTH=450 HEIGHT=35>
<PARAM NAME="name" value="old pal">
. . .
</applet>
Browser Note: Although at least one Java-enabled
browser conducts a case-sensitive search, the expected behavior is for
the getApplet method to perform a case-insensitive search. For example,
getApplet("old pal") and getApplet("OLD PAL") should both find an applet
named "Old Pal".
Every applet is implemented by creating a subclass
of the Applet class. The following figure shows the inheritance hierarchy
of the Applet class. This hierarchy determines much of what an applet can
do and how, as you'll see on the next few pages.
The Life Cycle of an Applet
Below is the Simple applet.
You can't run applets.Here's what you'd see if
you could:
Note: Because some old browsers don't support
1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the
1.1 code). To run the 1.1 version of the applet, go to example-1dot1/Simple.html.
For more information about running applets, refer to About Our Examples.
Loading the Applet
You should see "initializing... starting..." above,
as the result of the applet being loaded. When an applet is loaded, here's
what happens:
? An instance of the applet's controlling class
(an Applet subclass) is created.
? The applet initializes itself.
? The applet starts running.
Leaving and Returning to the Applet's Page
When the user leaves the page -- for example,
to go to another page -- the applet has the option of stopping itself.
When the user returns to the page, the applet can start itself again. The
same sequence occurs when the user iconifies and then reopens the window
that contains the applet. (Other terms used instead of iconify are minaturize,
minimize, and close.)
Try this: Leave and then return to this page.
You'll see "stopping..." added to the applet output above, as the applet
is given the chance to stop itself. You'll also see "starting...", when
the applet is told to start itself again. Next, iconify this window, and
then open it again. Many window systems provide a button in the title bar
that lets you iconify the window. You should see "stopping...." and then
"starting...." added to the applet output.
Browser note: Some browsers reload the applet
when you return to its page. In at least one browser, a bug exists where
an applet can initialize itself more than once without being reloaded.
Reloading the Applet
Some browsers let the user reload applets, which
consists of unloading the applet and then loading it again. Before an applet
is unloaded, it's given the chance to stop itself and then to perform a
final cleanup, so that the applet can release any resources it holds. After
that, the applet is unloaded and then loaded again, as described in Loading
the Applet, above.
Try this: If your browser or other applet viewer
lets you easily reload applets, reload the applet. Look at the standard
output to see what happens when you reload the applet. (See Displaying
Short Status Strings..\appletsonly/showStatus.html..\appletsonly/showStatus.htmlfor
information about the standard output.) You should see "stopping..." and
"preparing for unloading..." when the applet is unloaded. You can't see
this in the applet GUI because the applet is unloaded before the text can
be displayed. When the applet is reloaded, you should see "initializing..."
and "starting...", just like when you loaded the applet for the first time.
Quitting the Browser
When the user quits the browser (or whatever application
is displaying the applet), the applet has the chance to stop itself and
do final cleanup before the browser exits.
Summary
An applet can react to major events in the following
ways:
? It can initialize itself.
? It can start running.
? It can stop running.
? It can perform a final cleanup, in preparation
for being unloaded.
The next page describes the four applet methods
that correspond to these four types of reactions.
What Applets Can and Can't Do
This page gives an overview of both the restrictions
applets face and the special capabilities they have. You'll find more details
in the Security Restrictions..\practical/security.html..\practical/security.html
lesson.
Security Restrictions
Every browser implements security policies to
keep applets from compromising system security. This section describes
the security policies that current browsers adhere to. However, the implementation
of the security policies differs from browser to browser. Also, security
policies are subject to change. For example, if a browser is developed
for use only in trusted environments, then its security policies will likely
be much more lax than those described here.
Current browsers impose the following restrictions
on any applet that is loaded over the network:
? An applet cannot load libraries or define native
methods.
? It cannot ordinarily read or write files on
the host that's executing it.
? It cannot make network connections except to
the host that it came from.
? It cannot start any program on the host that's
executing it.
? It cannot read certain system properties.
? Windows that an applet brings up look different
than windows that an application brings up.
Each browser has a SecurityManager object that
implements its security policies. When a SecurityManager detects a violation,
it throws a SecurityException. Your applet can catch this SecurityException
and react appropriately.
Applet Capabilities
The java.applet package provides an API that
gives applets some capabilities that applications don't have. For example,
applets can play sounds, which other programs can't do yet.
Here are some other things that current browers
and other applet viewers let applets do:
? Applets can usually make network connections
to the host they came from.
? Applets running within a Web browser can easily
cause HTML documents to be displayed.
? Applets can invoke public methods of other
applets on the same page.
? Applets that are loaded from the local file
system (from a directory in the user's CLASSPATH) have none of the restrictions
that applets loaded over the network do.
? Although most applets stop running once you
leave their page, they don't have to.
Finding and Loading Data Files
Whenever an applet needs to load some data from
a file that's specified with a relative URL (a URL that doesn't completely
specify the file's location), the applet usually uses either the code base
or the document base to form the complete URL. The code base, returned
by the Applet getCodeBase method, is a URL that specifies the directory
from which the applet's classes were loaded. The document base, returned
by the Applet getDocumentBase method, specifies the directory of the HTML
page that contains the applet.
Unless the <APPLET> tag specifies a code base,
both the code base and document base refer to the same directory on the
same server. For example, in the figure in Test Driving an Applet..\overview/test.html..\overview/test.html,
the code and document bases would both specify the someDirectory directory.
Data that the applet always needs, or needs to
rely on as a backup, is usually specified relative to the code base. Data
that the applet user specifies, often by using parameters, is usually specified
relative to the document base.
Note: For security reasons, browsers limit the
URLs from which untrusted applets can read. For example, most browsers
don't allow untrusted applets to use ".." to get to directories above the
code base or document base. Also, since untrusted applets can't read files
except those on the applet's originating host, the document base isn't
generally useful if the document and the untrusted applet are on different
servers.
The Applet class defines convenient forms of image-loading
and sound-loading methods that let you specify images and sounds relative
to a base URL. For example, assume an applet is set up with one of the
directory structures shown in the following figure.
To create an Image object using the a.gif image
file under imgDir, the applet can use the following code:
Image image = getImage(getCodeBase(), "imgDir/a.gif");
Practical Considerations when Writing Applets
Security Restrictions
One of the main goals of the Java environment
is to make browser users feel secure running any applet. To achieve this
goal, we've started out conservatively, restricting capabilities perhaps
more than necessary. As time passes, applets will probably get more and
more abilities.
This page tells you about the current applet
security restrictions, from the point of view of how they affect applet
design. For more information on applet security, you should refer to Marianne
Mueller's excellent document:
Frequently Asked Questions - Applet Securityhttp://java.sun.com/sfaq/http://java.sun.com/sfaq/
Each applet viewer has a SecurityManager object
that checks for applet security violations. When a SecurityManager detects
a violation, it creates and throws a SecurityException object. Generally,
the SecurityException constructor prints a warning message to the standard
output. An applet can catch SecurityExceptions and react appropriately,
such as by reassuring the user and by resorting to a "safer" (but less
ideal) way of accomplishing the task.
Some applet viewers swallow some SecurityExceptions,
so that the applet never gets the SecurityException. For example, the JDK
Applet Viewer's implementation of the AppletContext getApplet and getApplets
methods simply catches and ignores any SecurityExceptions. The user can
see an error message in the standard output, but at least the applet gets
a valid result from the methods. This makes some sense, since getApplets
should be able to return any valid applets it finds, even if it encounters
invalid ones. (The Applet Viewer considers an applet valid if it's loaded
from the same host as the applet that's calling getApplets.)
To learn about security managers and the kinds
of security violations they can check for, see Introducing the Security
Manager..\..\essential/system/securityIntro.html..\..\essential/system/securityIntro.html.
As the applet overview lesson mentioned, existing
applet viewers (including Web browsers) impose the following restrictions:
Applets cannot load libraries or define native
methods.
Applets can use only their own Java code and
the Java API the applet viewer provides. At a minimum, each applet viewer
must provide access to the API defined in the java.* packages.
An applet cannot ordinarily read or write files
on the host that is executing it.
The JDK Applet Viewer actually permits some user-specified
exceptions to this rule, but Netscape Navigator 2.0, for example, does
not. Applets in any applet viewer can read files specified with full URLs,
instead of by a filename. A workaround for not being to write files is
to have the applet forward data to an application on the host the applet
came from. This application can write the data files on its own host. See
Working with a Server-Side Application for more examples.
An applet cannot make network connections except
to the host that it came from.
The workaround for this restriction is to have
the applet work with an application on the host it came from. The application
can make its own connections anywhere on the network. See Using a Server
to Work Around Security Restrictions for an example.
An applet cannot start any program on the host
that is executing it.
Again, an applet can work with a server-side
application instead.
An applet cannot read certain system properties.
See Reading System Properties for more information.
Windows that an applet brings up look different
than windows that an application brings up.
Applet windows have some warning text and either
a colored bar or an image. This helps the user distinguish applet windows
from those of trusted applications.
The following figures show a window brought up
by a program that can run either as an applet or as an application. The
first figure shows what the window looks like when the program is run as
an application on the Solaris platform. The second figure shows the window
when the program runs as an applet within the Solaris Netscape Navigator
2.0 browser.
Working with a Server-Side Application
Applets, like other Java programs, can use the
API defined in the java.net package to communicate across the network.
The only difference is that, for security reasons, the only host an applet
can communicate with is the host it was delivered from.
Note: Depending on the networking environment
an applet is loaded into, and depending on the browser that runs the applet,
an applet might not be able to communicate with its originating host. For
example, browsers running on hosts inside firewalls often cannot get much
information about the world outside the firewall. As a result, some browsers
might not allow applet communication to hosts outside the firewall.
It's easy to find out which host an applet came
from. Just use the Applet getCodeBase method and the java.net.URL getHost
method, like this:
String host = getCodeBase().getHost();
Once you have the right host name, you can use
all the networking code that is documented in the Custom Networking..\..\networking/index.html..\..\networking/index.html
trail.
3: Design Considerations
When you begin a software project, ask yourself
these three questions:
? How do I want to deliver my software to users?
? How can I design an application that is accessible
to all potential users?
? How can I design an application that suits
a global audience and requires minimal effort to localize?
Choosing an Application or an Applet
At the beginning of the development process,
you must decide if you want to create a standalone application or an applet
that is displayed in a web browser. The following figure shows the different
environments for running applications and applets.
Figure 17 Environments for Applications and Applets
When deciding between an application and an applet,
the two main issues you need to consider are distribution and security,
including read and write permissions. If you decide to use an applet, you
must also decide whether to display your applet in the user's current browser
window or in a separate browser window.
For an example of an application that uses the
Java look and feel, see MetalEdit Application. For an example of an applet,
see Retirement Savings Calculator Applet. For a list of additional reading
on applets, see Design for Applets.
Distribution
When deciding how to distribute your software,
weigh the needs of both end users and administrators. Don't forget to consider
ease-of-use issues for:
? Initial distribution and installation of the
software
? Maintenance of the software
? Updates to the software
? Daily access to the software
At one extreme is the standalone application,
distributed on a CD-ROM disc or a floppy disk and installed on the end
user's local hard disk. Once the application is installed, users can easily
access it. In an enterprise environment, however, maintenance can be complicated
because separate copies of the application exist on each user's local computer.
Distribution of the original application and subsequent updates require
shipment of the software to, and installation by, multiple users.
In contrast, applets are simpler to distribute
and maintain because they are installed on a central web server. Using
a web browser on their local machines, users can access the latest version
of the applet from anywhere on the intranet or Internet. Users, however,
must download the applet over the network each time they start the applet.
If you are creating an applet, make sure that
your users have a browser that contains the JFC or that they are using
JavaTM Plug-In. That way, users will not have to download the JFC every
time they run the applet.
Security Issues
Another issue to consider is whether your software
needs to read and write files. Standalone Java applications can read or
write files on the user's hard disk just as other applications do. For
example, the MetalEdit application reads and writes documents on the user's
local disk.
In contrast, applets usually cannot access a
user's hard disk because they are intended for display on a web page, which
might come from an unknown source. Applets are better suited for tasks
that do not require access to a user's hard disk. For example, a web page
for a bank might offer an applet that calculates home mortgage payments
and prints results, but does not save files on the customer's hard disk.
You can also use applets as a front end to a
central database. For example, the Retirement Savings Calculator applet
enables company employees to select funds for their retirement contribution
and update the amount of their contribution in the company database.
Placement of Applets
If you decide to design an applet, you can display
your applet in the user's current browser window or in a separate browser
window.
Applets in the User's Current Browser Window
The current browser window is well suited for
displaying applets in which users perform a single task. This approach
enables users to perform the task and then resume other activities in the
browser, such as surfing the web.
An applet displayed in the current browser window
should not include a menu bar--having a menu bar in both the applet and
the browser might confuse users. The mnemonics assigned in the applet must
also be different from the mnemonics used to control the browser window;
otherwise, the mnemonics might conflict.
A disadvantage of using the current browser window
is that the applet terminates when users navigate to another web page.
The current settings and data in the applet are lost. To use the applet
again, users must navigate back to the page that contains the applet and
reload the page.
Applets in Separate Browser Windows
If your applet involves more than one task or
if users might visit other web pages before completing the task, launch
a separate browser window and display the applet there. This approach enables
users to interact with the applet and maintain the original browser window
for other activities. Navigating to another web page in the original browser
window does not affect the applet in the separate browser window.
Designing an applet for a separate browser window
is simpler if you remove the browser's normal menu and navigation controls.
Doing so avoids confusion between the browser's menu and controls and the
applet's menus and controls. You also avoid potential conflicts between
mnemonics in the two windows.
CORBA Architecture Overview
Overview of CORBA
The Common Object Request Broker Architecture
(CORBA) is an emerging open distributed object computing infrastructure
being standardized by the Object Management Group. CORBA automates many
common network programming tasks such as object registration, location,
and activation; request demultiplexing; framing and error-handling; parameter
marshalling and demarshalling; and operation dispatching.
The following figure illustrates the primary components
in the OMG Reference Model architecture. Descriptions of these components
are available further below. Portions of these descriptions are based on
material from
Object Services -- These are domain-independent
interfaces that are used by many distributed object programs. For example,
a service providing for the discovery of other available services is almost
always necessary regardless of the application domain. Two examples of
Object Services that fulfill this role are:
? The Naming Service -- which allows clients
to find objects based on names;
? The Trading Service -- which allows clients
to find objects based on their properties.
There are also Object Service specifications
for lifecycle management, security, transactions, and event notification,
as well as many others
Common Facilities -- Like Object Service interfaces,
these interfaces are also horizontally-oriented, but unlike Object Services
they are oriented towards end-user applications. An example of such a facility
is the Distributed Document Component Facility (DDCF), a compound document
Common Facility based on OpenDoc. DDCF allows for the presentation and
interchange of objects based on a document model, for example, facilitating
the linking of a spreadsheet object into a report document.
? Domain Interfaces -- These interfaces fill
roles similar to Object Services and Common Facilities but are oriented
towards specific application domains. For example, one of the first OMG
RFPs issued for Domain Interfaces is for Product Data Management (PDM)
Enablers for the manufacturing domain. Other OMG RFPs will soon be issued
in the telecommunications, medical, and financial domains.
? Application Interfaces - These are interfaces
developed specifically for a given application. Because they are application-specific,
and because the OMG does not develop applications (only specifications),
these interfaces are not standardized. However, if over time it appears
that certain broadly useful services emerge out of a particular application
domain, they might become candidates for future OMG standardization.
CORBA ORB Architecture
The following figure illustrates the primary
components in the CORBA ORB architecture. Descriptions of these components
are available below the figure.
Figure 2. CORBA ORB Architecture
?
?
?
?
?
?
? Object Implementation -- This defines operations
that implement a CORBA IDL interface. Object implementations can be written
in a variety of languages including C, C++, Java, Smalltalk, and Ada.
? Client -- This is the program entity that invokes
an operation on an object implementation. Accessing the services of a remote
object should be transparent to the caller. Ideally, it should be as simple
as calling a method on an object, i.e., obj->op(args). The remaining components
in Figure 2 help to support this level of transparency.
? Object Request Broker (ORB) -- The ORB provides
a mechanism for transparently communicating client requests to target object
implementations. The ORB simplifies distributed programming by decoupling
the client from the details of the method invocations. This makes client
requests appear to be local procedure calls. When a client invokes an operation,
the ORB is responsible for finding the object implementation, transparently
activating it if necessary, delivering the request to the object, and returning
any response to the caller.
? ORB Interface -- An ORB is a logical entity
that may be implemented in various ways (such as one or more processes
or a set of libraries). To decouple applications from implementation details,
the CORBA specification defines an abstract interface for an ORB. This
interface provides various helper functions such as converting object references
to strings and vice versa, and creating argument lists for requests made
through the dynamic invocation interface described below.
? CORBA IDL stubs and skeletons -- CORBA IDL
stubs and skeletons serve as the ``glue'' between the client and server
applications, respectively, and the ORB. The transformation between CORBA
IDL definitions and the target programming language is automated by a CORBA
IDL compiler. The use of a compiler reduces the potential for inconsistencies
between client stubs and server skeletons and increases opportunities for
automated compiler optimizations.
? Dynamic Invocation Interface (DII) -- This
interface allows a client to directly access the underlying request mechanisms
provided by an ORB. Applications use the DII to dynamically issue requests
to objects without requiring IDL interface-specific stubs to be linked
in. Unlike IDL stubs (which only allow RPC-style requests), the DII also
allows clients to make non-blocking deferred synchronous (separate send
and receive operations) and oneway (send-only) calls.
? Dynamic Skeleton Interface (DSI) -- This is
the server side's analogue to the client side's DII. The DSI allows an
ORB to deliver requests to an object implementation that does not have
compile-time knowledge of the type of the object it is implementing. The
client making the request has no idea whether the implementation is using
the type-specific IDL skeletons or is using the dynamic skeletons.
?
?
?
?
? Object Adapter -- This assists the ORB with
delivering requests to the object and with activating the object. More
importantly, an object adapter associates object implementations with the
ORB. Object adapters can be specialized to provide support for certain
object implementation styles (such as OODB object adapters for persistence
and library object adapters for non-remote objects).
JAR (Java Archive) bundling of resources for a
single HTTP transaction
JAR is a new JDK 1.1 platform-independent file
format that aggregates many files into one. Java applets and their requisite
components--such as class files, images and sounds--can be bundled into
a compressed JAR file and downloaded to a browser in a single HTTP transaction
to reduce download time. In addition, applet authors can digitally sign
individual entries in a JAR file to authenticate their origin.
Communication Between Applets and Servlets: Establishing
a Channel
Java applets provide a unique platform for creating
lively applications that are accessible via the browser. While there are
self-contained applets that dazzle Web pages with special effects, most
applets require connectivity to data sources and other applications to
accomplish their tasks. There are, however, inherent architectural and
technical issues for applets that require connectivity to other resources.
For example, the security model used by browsers
to run Java applets restricts their network connections. Another factor
is the inconsistency of JVM implementations in various browsers. There
is also a noticeable delay between the time a new Java version is made
available and its integration in the popular browsers.
Sun has attempted to address these issues by
creating the Java Plug-in. The plug-in is made by Sun and is usually available
shortly after a new version of the JDK is released. The Plug-in replaces
the internal JVM used by the browser. While this approach works in somewhat
controlled environments, it has its own problems when it comes to the huge
Internet audience.
At the very least, in order for this model to
be successful, one has to assume that everyone has installed the latest
version of the Java Plug-in on their machines. Again, while this assumption
may make sense in an intranet environment, it can not be applied to the
broad Internet audience. There is also some slight modifications in the
HTML code containing the Java applet that is needed to take advantage of
the Plug-in environment.
So what we are left with is a good technology
with limitations on its deployment. I have seen my share of projects that
have stalled due to deployment issues of Java applets. The project managers
assumed that by a certain date a particular version of Java would be widely
supported by browsers, and when that assumption failed to materialize,
so did their deployment plans.
Alternative Approaches
Many experts (including those from Sun itself)
indicate that their preference is to use Java on the server and rely on
HTML to create the GUI that is to run on the browser. That approach may
make sense for a number of sites, but there are instances where HTML (or
even DHTML) simply cannot replace the richness and the interactivity that
a live program (i.e., a Java applet) can provide. Applications that rely
on rich presentation slides, real-time graphs and statistics, and sophisticated
user interfaces rely on Java applets. So one approach that has seen success
is not to abandon Java applets altogether, but to limit the functionality
of an applet and rely more on back-end resources.
For example, instead of having the applet perform
time-consuming calculations and then drawing a graph, have a back-end program
do the calculations and then send to the applet just the necessary data
to draw the graph. Of course, this approach requires connectivity between
the applet and server-side programs — which is the topic of this article.
There are a number of mechanisms where applets
and server-side programs like servlets can communicate with each other.
For example, an applet can make RMI calls to server-side processes or use
CORBA to activate remote methods. Architecturally, process separation using
remote objects is an elegant solution, but there are deployment issues
with both CORBA and RMI. Many corporate firewalls block such traffic which
in effect eliminates the above technologies as a communication choice.
Another approach would be to refresh the HTML
page containing the applet and pass new parameters to it. In this scenario,
the server-side process would repaint the entire HTML page at a given time
interval. As part of the repainting, the parameters to the applet are updated.
The applet will then display itself based on the new parameters. This is
a one-way communication channel (the server sends messages to the applet)
and is also very inefficient.
Relying on HTTP
The communication channel between an applet and
a servlet must be simple and deployable in various environments. If you
look at the essence of such communication, it typically involves the applet
initiating a request to the server-side program. This request contains
some data. The server-side program must receive the request, interpret
it and send a response back to the applet. What I have just described is
identical to how a browser communicates with a Web server through HTTP.
Java has built-in support for both HTTP and URL-based connections. So all
we have to do is to open a connection to a servlet specified by an URL
and send data to it. Granted, HTTP is not the most efficient protocol,
but it does provide a channel through which data exchange can be done and
that is what we are after.
Due to the applet security model, there is a
restriction with the above approach. The applet can only communicate back
to the server from which it came from. So wherever our server-side process
is running, that's where the applet must come from. The server-side program
is free to open channels to other resources such as remote databases, CORBA
objects, EJB servers, etc. So from the design perspective, we can still
utilize the benefits that remote objects provide.
The applet must know the URL of the server-side
process. For our purposes, we use a servlet, but CGI scripts, JSP, ASP,
or other server-side processes that can communicate via HTTP can be used.
Once we have the URL, we can open a connection and send data:
String urlAddress =
"http://www.someurl.com/someServlet"
java.net.URL url =
new java.net.URL(urlAddress);
java.net.URLConnection
c = url.openConnection();
This will give us the communication channel to
the servlet. What we have to do next is to send the servlet some data in
the context of a request. We don't want to restrict ourselves to a particular
data type. To facilitate this, we create an output stream and write our
data in terms of bytes to it. Note that an instance of the ByteArrayOutputStream
is used to create the actual DataOutputStream. If you look at the DataOutputStream
class, you'll see a number of "write" methods for various data types. We
use the writeUTF() method to write a simple text message.
ByteArrayOutputStream
bytesOut = new ByteArrayOutputStream();
DataOutputStream out
= new DataOutputStream(bytesOut);
out.writeUTF("Hello World");
out.flush();
Before sending our message, we need to calculate
its size. To do that, we create an array of bytes that will store our data.
The length of that array is the size of our data. We also need to specify
in our request the MIME type and the length of the request message data.
byte buffer[] =
bytesOut.toByteArray();
c.setRequestProperty("Content-type",
";application/octet-stream");
c.setRequestProperty("Content-length",
"" + buffer.length);
Finally, we can create a new DataOutputStream
to write the data to the connection we established earlier. The data we
are writing out is simply the array of bytes we created earlier.
DataOutputStream
out2 = new DataOutputStream(c.getOutputStream());
out2.write(buffer)
Conclusion
What we have shown are the steps an applet must
complete to establish a communication channel to a servlet (or any server-side
Web program). In the next part of the article, we'll present an applet/servlet
combination that use the above technique to send messages. There are a
number of variations to the above method and while we are using a simple
text message for our example, the message can be an XML document, a serialized
object, or some other complex data.
|
|
Contents |
Previous |
Next |
Home
|
Last Modified on : 3/9/2001 by PRR
|
|
Contact
prasks
with questions or suggestion.
All rights reserved.
Terms
of use.
All products and companies mentioned at this site are trademarks of
their respective owners.
|
|