The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: JDBC(TM) Database Access
Lesson: JDBC Basics

## Creating an Applet from an Application

> Suppose that the owner of The Coffee Break wants to display his current coffee prices in an applet on his web page. He can be sure of always displaying the most current price by having the applet get the price directly from his database.

> In order to do this, he needs to create two files of code, one with applet code, and one with HTML code. The applet code contains the JDBC code that would appear in a regular application plus additional code for running the applet and displaying the results of the database query. In our example, the applet code is in the file ``OutputApplet.java``. To display our applet in an HTML page, the file `OutputApplet.html` tells the browser what to display and where to display it.

> The rest of this section will tell you about various elements found in applet code that are not present in standalone application code. Some of these elements involve advanced aspects of the Java programming language. We will give you some rationale and some basic explanation, but explaining them fully is beyond the scope of this tutorial. For purposes of this sample applet, you only need to grasp the general idea, so don't worry if you don't understand everything. You can use the applet code as a template, substituting your own queries for the one in the applet.

### Writing Applet Code

> To begin with, applets will import classes not used by standalone applications. Our applet imports two classes that are special to applets: the class `Applet` , which is part of the `java.applet` package, and the class `Graphics` , which is part of the `java.awt` package. This applet also imports the general-purpose class `java.util.Vector` so that we have access to an array-like container whose size can be modified. This code uses `Vector` objects to store query results so that they can be displayed later.

> All applets extend the `Applet` class; that is, they are subclasses of `Applet` . Therefore, every applet definition must contain the words `extends` `Applet` , as shown here:

> >     public class MyAppletName extends Applet {
> >         . . .
> >     }

> In our applet example, `OutputApplet`, this line also includes the words `implements` `Runnable` , so it looks like this:

> >     public class OutputApplet extends Applet implements Runnable {
> >         . . .
> >     }

> `Runnable` is an interface that makes it possible to run more than one thread at a time. A thread is a sequential flow of control, and it is possible for a program to be multithreaded, that is, to have many threads doing different things concurrently. The class `OutputApplet` implements the interface `Runnable` by defining the method `run` , the only method in `Runnable` . In our example the `run` method contains the JDBC code for opening a connection, executing a query, and getting the results from the result set. Since database connections can be slow, and can sometimes take several seconds, it is generally a good idea to structure an applet so that it can handle the database work in a separate thread.

> Similar to a standalone application, which must have a `main` method, an applet must implement at least one `init` , `start` , or `paint` method. Our example applet defines a `start` method and a `paint` method. Every time `start` is invoked, it creates a new thread (named `worker` ) to re-evaluate the database query. Every time `paint` is invoked, it displays either the query results or a string describing the current status of the applet.

> As stated previously, the `run` method defined in `OutputApplet` contains the JDBC code. When the thread `worker` invokes the method `start` , the `run` method is called automatically, and it executes the JDBC code in the thread `worker` . The code in `run` is very similar to the code you have seen in our other sample code with three exceptions. First, it uses the class `Vector` to store the results of the query. Second, it does not print out the results but rather adds them to the `Vector` `results` for display later. Third, it likewise does not print out exceptions and instead records error messages for later display.

> Applets have various ways of drawing, or displaying, their content. This applet, a very simple one that has only text, uses the method `drawString` (part of the `Graphics` class) to display its text. The method `drawString` takes three arguments: (1) the string to be displayed, (2) the `x` coordinate, indicating the horizontal starting point for displaying the string, and (3) the `y` coordinate, indicating the vertical starting point for displaying the string (which is below the text).

> The method `paint` is what actually displays something on the screen, and in `OutputApplet.java` , it is defined to contain calls to the method `drawString` . The main thing `drawString` displays is the contents of the `Vector` `results` (the stored query results). When there are no query results to display, `drawString` will display the current contents of the `String` `message` . This string will be "Initializing" to begin with. It gets set to "Connecting to database" when the method `start` is called, and the method `setError` sets it to an error message when an exception is caught. Thus, if the database connection takes much time, the person viewing this applet will see the message "Connecting to database" because that will be the contents of `message` at that time. (The method `paint` is called by AWT when it wants the applet to display its current state on the screen.)

> The last two methods defined in the class `OutputApplet,` `setError` and `setResults` are private, which means that they can be used only by `OutputApplet`. These methods both invoke the method `repaint` , which clears the screen and calls `paint` . So if `setResults` calls `repaint` , the query results will be displayed, and if `setError` calls `repaint` , an error message will be displayed.

> A final point to be made is that all the methods defined in `OutputApplet` except `run` are `synchronized` . The keyword `synchronized` indicates that while a method is accessing an object, other `synchronized` methods are blocked from accessing that object. The method `run` is not declared `synchronized` so that the applet can still paint itself on the screen while the database connection is in progress. If the database access methods were `synchronized` , they would prevent the applet from being repainted while they are executing, and that could result in delays with no accompanying status message.

> To summarize, in an applet, it is good programming practice to do some things you would not need to do in a standalone application:

> 1. Put your JDBC code in a separate thread
> 2. Display status messages on the screen during any delays, such as when a database connection is taking a long time
> 3. Display error messages on the screen instead of printing them to `System.out` or `System.err` .

### Running an Applet

> Before running our sample applet, you need to compile the file `OutputApplet.java` . This creates the file `OutputApplet.class` , which is referenced by the file `OutputApplet.html`.

> The easiest way to run an applet is to use the appletviewer, which is included as part of the JDK. Simply follow the instructions below for your platform to compile and run `OutputApplet.java` :

> UNIX

>   >     javac OutputApplet.java
>   >     appletviewer OutputApplet.html

> Windows 95/NT

>   >     javac OutputApplet.java
>   >     appletviewer OutputApplet.html

> Applets loaded over the network are subject to various security restrictions. Although this can seem bothersome at times, it is absolutely necessary for network security, and security is one of the major advantages of using the Java programming language. An applet cannot make network connections except to the host it came from unless the browser allows it. Whether one is able to treat locally installed applets as "trusted" also depends on the security restrictions imposed by the browser. An applet cannot ordinarily read or write files on the host that is executing it, and it cannot load libraries or define native methods.

> Applets can usually make network connections to the host they came from, so they can work very well on intranets.

> The JDBC-ODBC Bridge driver is a somewhat special case. It can be used quite successfully for intranet access, but it requires that ODBC, the bridge, the bridge native library, and JDBC be installed on every client. With this configuration, intranet access works from Java applications and from trusted applets. However, since the bridge requires special client configuration, it is not practical to run applets on the Internet with the JDBC-ODBC Bridge driver. Note that this is a limitation of the JDBC-ODBC Bridge, not of JDBC. With a pure Java JDBC driver, you do not need any special configuration to run applets on the Internet.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.