|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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
. To display our applet in an HTML page, the fileOutputApplet.javaOutputApplet.htmltells 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.
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 thejava.appletpackage, and the classGraphics, which is part of thejava.awtpackage. This applet also imports the general-purpose classjava.util.Vectorso that we have access to an array-like container whose size can be modified. This code usesVectorobjects to store query results so that they can be displayed later.All applets extend the
Appletclass; that is, they are subclasses ofApplet. Therefore, every applet definition must contain the wordsextendsApplet, as shown here:public class MyAppletName extends Applet { . . . }In our applet example,
OutputApplet, this line also includes the words
implementsRunnable, so it looks like this:public class OutputApplet extends Applet implements Runnable { . . . }
Runnableis 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 classOutputAppletimplements the interfaceRunnableby defining the methodrun, the only method inRunnable. In our example therunmethod 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
mainmethod, an applet must implement at least oneinit,start, orpaintmethod. Our example applet defines astartmethod and apaintmethod. Every timestartis invoked, it creates a new thread (namedworker) to re-evaluate the database query. Every timepaintis invoked, it displays either the query results or a string describing the current status of the applet.As stated previously, the
runmethod defined inOutputAppletcontains the JDBC code. When the threadworkerinvokes the methodstart, therunmethod is called automatically, and it executes the JDBC code in the threadworker. The code inrunis very similar to the code you have seen in our other sample code with three exceptions. First, it uses the classVectorto store the results of the query. Second, it does not print out the results but rather adds them to theVectorresultsfor 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 theGraphicsclass) to display its text. The methoddrawStringtakes three arguments: (1) the string to be displayed, (2) thexcoordinate, indicating the horizontal starting point for displaying the string, and (3) theycoordinate, indicating the vertical starting point for displaying the string (which is below the text).The method
paintis what actually displays something on the screen, and inOutputApplet.java, it is defined to contain calls to the methoddrawString. The main thingdrawStringdisplays is the contents of theVectorresults(the stored query results). When there are no query results to display,drawStringwill display the current contents of theStringmessage. This string will be "Initializing" to begin with. It gets set to "Connecting to database" when the methodstartis called, and the methodsetErrorsets 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 ofmessageat that time. (The methodpaintis 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,setErrorandsetResultsare private, which means that they can be used only byOutputApplet. These methods both invoke the methodrepaint, which clears the screen and callspaint. So ifsetResultscallsrepaint, the query results will be displayed, and ifsetErrorcallsrepaint, an error message will be displayed.A final point to be made is that all the methods defined in
OutputAppletexceptrunaresynchronized. The keywordsynchronizedindicates that while a method is accessing an object, othersynchronizedmethods are blocked from accessing that object. The methodrunis not declaredsynchronizedso that the applet can still paint itself on the screen while the database connection is in progress. If the database access methods weresynchronized, 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:
Before running our sample applet, you need to compile the file
OutputApplet.java. This creates the fileOutputApplet.class, which is referenced by the fileOutputApplet.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.htmlApplets 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-2004 Sun Microsystems, Inc. All rights reserved.