Applets


1) How can I download a file (for instance, a Microsoft Word document) from a server using a servlet and an applet?
Try telling the applet to call getAppletContext().showDocument("http://foo.com/whatever/blah.doc"). That makes the browser responsible for fetching and saving the document (including putting up the "Save As" dialog).
You may also want to check the web server configuration to make sure the approprate MIME-type configuration is set. If your servlet is the one fetching the document (or creating it on the fly), then it must set the MIME-type using response.setContentType("application/ms-word") or equivalent.
2) How do I get an applet to load a new page into the browser?
In short, get the applet's context and tell it to show a different document: getAppletContext().showDocument(new URL("http://foo.com/whatever/blah.doc")). You can also provide a target frame string as in getAppletContext().showDocument(new URL("http://foo.com/whatever/blah.doc"), "target"). There are four special targets strings. Any other string will act as a named top-level window, if the frame doesn't exist.
"_self" Show in same frame as applet
"_parent" Show in the applet's parent frame
"_top" Show in the top-level frame of the applet's window
"_blank" Show in a new, unnamed top-level window

3) What is the syntax of the tag?
// Required
CODE = appletClass or
OBJECT = serializedApplet
HEIGHT = pixels
WIDTH = pixels

// Options
CODEBASE = codebaseURL
ARCHIVE = archiveList
ALT = alternateText
NAME = instanceName
ALIGN = alignment
HSPACE = pixels
VSPACE = pixels
>


...
Alternate HTML

Support for OBJECT is limited.
4) How do I create an applet that accepts an unlimited number of parameters?
While there is some upper bounds to the number of parameters the browser will let you specify, if you would like to let a user specify an undefined number of values, you can let them specify a parameter with a number at the end and keep counting until no more parameters following that pattern are there, as in:




To do this, you just increment a counter for the getParameter() calls:
import java.applet.*;

public class Params extends Applet {
public void init() {
String value;
int i = 0;
while ((value = getParameter("Param" + i)) != null) {
System.out.println ("Param" + i + ": " + value);
i++;
}
}
}

5) How can I connect from an applet to a database on the server?

There are two ways of connecting to a database on the server side.
1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.
2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
6) How do I display a message in the browser's status bar?
To show a message in the status bar, you would call the showStatus() method of the AppletContext:
getAppletContext().showStatus(message);
Keep in mind that the browser can overwrite the message at any time or the browser might not have a visible status bar. This basically means you should not use the status bar for messages that might be missed.
7) What are the main differences between applets and applications?
Applets are created to be embedded within a browser. As such, they have methods that are automatically called by the browser at certain times: init() when first loaded, start() when page loaded/entered, stop() when page left, destroy() when applet unloaded, and paint() when the screen needs to be displayed. In addition, applets have severe security restrictions as they can be loaded from untrusted sources over the Internet. Applications on the other hand need to be installed locally, start execution with the main() method, and have no inherent security restrictions. Beyond this, applications control their own operations.
8) How can I get the real local host IP address in an applet?

Applet security restrictions do not let you get this in an untrusted applet via InetAddress.getLocalHost().
However, you can get this address by creating a Socket connection back to the web server from which you came and asking the Socket for the local address:
URL url = getDocumentBase();
String host = url.getHost();
Socket socket = new Socket(host, 80);
InetAddress addr = socket.getLocalAddress();
String hostAddr = addr.getHostAddress();
System.out.println("Addr: " + hostAddr);

9) How do I load a serialized applet?

Instead of specifying the CODE attribute of an tag, you use the OBJECT attribute, as in:
OBJECT=TheApplet.ser
WIDTH=300
HEIGHT=300
>

This allows you to preinitialize your applet to some saved state, instead of having to reinitialize your applet each time it is loaded.
Support for this in browsers is severly limited. Don't rely on it.
10) From one applet, how do I communicate with another applet loaded from the same server?
It really doesn't matter that they are loaded from the same server, as long as they are running in the same JVM in the browser, you can call methods between them.
If you include a name="appletA" value in the applet tag of the applet you want to call methods on, you get a reference to it by using the AppletContext:
MyApplet appl = (MyApplet) getAppletContext().getApplet("appletA");
if (null != appl) {
appl.register("Hello there!", this);
}
Checking that you get a reference to the class you expect is left as an exercize to the reader :-)
1) In an applet, is the start() or paint() method executed first?
The initial order in which the lifecycle methods of applets are executed when loaded is:
init()
start()
paint()
And when done:
stop()
destroy()
This also holds when you call repaint() in the init() method. However, the init() method will not be called if you load a serialized applet.
2) What are the main differences between JavaBeans and applets?
Applets are Java programs which are meant to be run by an applet-runner (which is typically inside a web browser). By definition, applets are applets because they inherit from java.applet.Applet. Also, applets are pretty constrained in what they are/aren't allowed to do.
Traditional JavaBeans are Java software components. A bean may be a single, simple, standalone class or it may be a complicated behemoth but, as long as it follows the rules and conventions of JavaBeans, then it's a JavaBean.
3) How do I use an applet that resides on a remote machine?
You would specify the location of the class files in the CODEBASE attribute of the tag:
width = 300 height = 300
CODEBASE="http://www.jguru.com/appletdirectory/">


4) When you communicate with a servlet from an Applet or an application, how can you ensure that the session information is preserved? That is, how do you manage cookies in applet-servlet communication?

For sessions, your best bet is to have the servlet rewrite the URLs to include the session information. With cookies read I am writing an application that retrieves a URL, but that URL requires a cookie. Is there a way to hold that cookie within my application and send it back to the URL when requested? Essentially, you can send the cookie back easily with HTTP. For instance, urlConnection.setRequestProperty("cookie",_cookie); Where the _cookie is coming from a previous call: String _cookie = urlConnection.getHeaderField("set-cookie");

5) How can I change my application into applet?
 Create a subclass of java.applet.Applet
 Take the code in the main() method of the application and move it to the init() method of the applet
 Create an HTML file to load the applet
 If necessary, move any requirements that untrusted applets cannot do into an appropriate server-side task
 If necessary, modify all getting of support files
 Test
6) In detail, how do the applet life cycle methods init(), start(), paint(), stop(), and destroy() work?
The life cycle methods of an applet are init(), start(), stop(), and destroy(). While frequently grouped with the methods, the paint() method is not really part of the applet's life cycle. The method is just called by the browser whenever a part of the screen has become invalidated or in response to a programmer-generated repaint request. The update() method falls into the same category as paint().
As far as the other methods go:
 init() - called once when applet is loaded
 start() - called every time the page the applet is located on is loaded, after init() or after leaving the page and returning
 stop() - called every time the page the applet is located on is left
 destroy() - called when applet is unloaded
If loading a serialized version of an applet from a .ser file (OBJECT attribute in tag instead of CODE attribute), the init() method is not called.
Use the start() / stop() method pair to deal with starting and stopping threads, as when the page isn't active it isn't nice to use up resources.
Don't rely on the destroy() method being called to free a crucial resource, in case the browser crashes.
I had heard that start() / stop() were called for iconifying and deiconifying, but a test with the latest browser versions shows they aren't called.
7) How does an applet get loaded into the browser?
The browser’s HTML interpreter reads the parameters from the APPLET tag. The relevant parameters used to load the applet’s class are CODE, CODEBASE, and ARCHIVE (CODEBASE and ARCHIVE are optional - OBJECT can be used instead of CODE). The CODE parameter holds the name of the applet’s class file. The CODEBASE holds the class file directory (the default is the current directory), and the ARCHIVE is the name of a jar or zip file that the applet’s class files are stored in (the default is no archive).
The browser then reads the byte code from the class files and performs a verification pass, checking for access violations and invalid opcodes (among other things). The Java Virtual Machine (JVM) then builds an object for each class (provided the objects have not been created by a previous instance), and executes any static code in each object’s initialization section. Object initialization also includes the construction of the superclass objects (the superclass files from Applet to Object are typically loaded from the browser’s own Java API on the local file system).
If the applet makes it this far without generating security exceptions, missing class errors, or common errors in static code segments, the JVM will make calls to initialization functions in the superclass, then to the applet’s init() member.
8) What is needed in the APPLET tag to cause an applet to be loaded from a JAR file?
To specify an that an applet loads from a JAR file, instead of from separate classes, add an ARCHIVE attribute to your tag:

CODE=AppletClass
ARCHIVE="foo.jar"
WIDTH=200
HEIGHT=200>

If you need to specify multiple JAR files, provide a comma separated list.
9) When should one use applets and when should one use servlets?
Applets run inside browsers, and servlets run inside servers. So broadly speaking, use applets when you need dynamism on the client side, and use servlets when you need dynamism on the server side.
Servlets can produce any HTML (or indeed, any file type), and therefore are much more versatile than applets. Servlets can tailor the HTML they produce based on the browser type (as specified in the "User-Agent" header), and thus can produce output that will work in virtually any client, including WAP browsers or the like. Applets are notoriously poorly supported, and even in browsers that ostensibly have Java support, don't work consistently.
Servlets can also produce HTML with embedded JavaScript, which allows a fair amount of dynamic behavior on browsers which support it.
However, due to the infuriating limitations and bugs in JavaScript, sometimes you've just got to have an applet to get the client-side behavior you want. In these cases, take comfort in the fact that you can generate HTML containing APPLET tags from inside a servlet.
10) Why do I not create a constructor for an applet?
One doesn't see constructors in applets because the applet container doesn't guarantee a complete environment (valid applet context) until the init() method is called.
11) Why doesn't appletviewer appletclass.class work?
Applets are loaded with an HTML file. You need to specify an tag in the .html file to load the APPLET.
12) What are the differences between trusted and untrusted applets?
In general, applets loaded over the net are prevented from accessing files on the client machine, and from making network connections except to the host originating the applet.
In addition, applets loaded over the network are prevented from starting other programs on the client. Applets loaded over the network are also not allowed to load libraries, or to define native method calls, providing accessing to the underlying computer.
On the other hand, trusted applets can be permitted to do all that. The trust model in Java allows you to enable only certain operations, so it is possible that you enable network connections to/from anywhere but don't permit access to the local file system.
How to enable trusting an applet is different for each browser, IE, Netscape, and standard Java with the Plug-in.
13) Why doesn't an applet viewed through the browser respond to keyboard events, but the same works fine from within appletviewer?
In order to respond to keyboard events your applet needs to have the input focus. In the case of appletviewer, there is nothing else on the page that might have focus. In the case of a browser, there is. Just click into the applet's area to have it get the input focus and then it will respond to keyboard events.
14) What is the Java Plug-In?

The Plug-in is a replacement Java Runtime Environment for your browser. It allows you to upgrade the browser's supported Java version without waiting for the browser vendor to release a new version of the browser.
15) How do I automatically set the input focus in my applet to a specific component/text field when the browser loads the page that contains the applet?

The java.awt.Component class has a method named requestFocus(), you can use this to request focus on any component.

16) What is an applet stub?
An applet stub is an interface that the applet container (browser) creator will implement abstracting out capabilities like getting applet parameters, the applet's code/document base and other information necessary for the contained applet(s). As an applet program, you'll rarely use the interface. The only time you really run across a need to do anything with the interface is if you try to run your applet in your own container. You'll then have to implement the AppletStub interface yourself, along with the AppletContext interface.
17) How do I stop an applet from running?
Browsers will constantly call the applet life-cycle methods. There is no way to stop them. The only way to stop an applet from running / displaying anything / taking up CPU time is to set a flag in the code and check it within each of the life-cycle methods. Calling destroy() is not something you as a user / developer should do. Calling the method is the responsibility of the applet container (the browser) when it wants to unload the applet.
18) How can an applet get information about the URL it was called from?
The getDocumentBase() method of Applet returns the base URL of the HTML file that loaded an applet. It is frequently used in conjunction with getting supplemental files like images, as in Image image = getImage(getDocumentBase(), "foo.gif");
While in most cases it returns the full URL of the HTML file that loaded the applet, the API docs specify that it only needs to return the URL for the directory of the file.
19) What is an applet?
Basically, an applet is a Java class, extending from java.applet.Applet that runs in a Web browser, loaded from an APPLET tag in an HTML file. The browser then calls applet life-cycle methods like start(), stop(), init(), and destroy() as needed. There are security restrictions untrusted applets must abide by, like not being able to connect to anywhere besides the web server from which it came.
20) What API changes are there for applets with JDK 1.4?
The constructor for the Applet class now throws a HeadlessException.
Also, the AppletContext interface now has three new methods: setStream(), getStream(), and getStreamKeys().
21) Are there any restrictions placed on applets loaded from HTML pages generated from servlets / JSP pages?
It is good practice to include the CODEBASE attribute in the APPLET tag and specify a directory other then the servlet directory for storing the applet-related classes. For example:
out.println(<"APPLET CODE=Foo.class CODEBASE=/applets WIDTH=400 HEIGHT=400">);
Some Web servers think that all classes loaded from the servlets directory are automatically servlets, thus causing the applet not to load.
22) How can I easily provide default values for when applet parameters are not specified?
Here's a helper method that you can use to do that:
import java.applet.*;

public class AppletUtils {
private AppletUtils() {}

public static String getParameter(
Applet applet, String key, String keyDefault) {

String value = applet.getParameter(key);

return (value == null) ? keyDefault : value;

}
}
Here's how to call:
String var = AppletUtils.getParameter(this, "name", "Jaeger");

23) What is the default layout manager of an applet?

For a java.applet.Applet, the default layout manager is FlowLayout.
For the content pane of a javax.swing.JApplet, the default layout manager is a BorderLayout.
24) My applet runs fine with appletviewer but not in the browser, what can be the problem?
Applets loaded through appletviewer are more then likely loading their classes from the local CLASSPATH, not over the network. As such, they get different permissions and can do things that applets loaded over the network cannot. Try using Tomcat and serving the Applet through an HTTP connection, instead of loading the .HTML file from the file system.
Also, Java runtimes in browsers are based on Java 1.1.x. If you need to use newer capabilities, you'll need to use the Java Plug-in. Without it, you're stuck with the older Java runtime capabilities.
25) What does the class hierarchy of the Applet class look like?

The inheritence hierarchy of the java.applet.Applet class is as follows:
+-----------+
| Object |
+-----------+
|
+-----------+
| Component |
+-----------+
|
+-----------+
| Container |
+-----------+
|
+-----------+
| Panel |
+-----------+
|
+-----------+
| Applet |
+-----------+

26) How can I maintain a single instance of an object in an applet?
In start(), instead of always creating a new object, return the existing one if it exists or create a new one if it doesn't.

No comments: