21 Applets and Web Programming As noted in Chapter 2, although Java is a general purpose programming language that can be used to create almost any type of computer program, much of the excitement surrounding Java has been generated by its employment as a language for creating programs intended for execution across the World Wide Web. Programs written for this purpose must follow certain conventions, and they diæer slightly from programs designed to be executed directly on a computer, such as the ones we have developed up to now. In this chapter we will examine these diæerences and see how to create programs for the Web. 21.1 Applets and HTML Applications written for the World Wide Web are commonly referred to as applets. Applets are attached to documents distributed over the World Wide Web. These documents are written using the HyperText Markup Language èhtmlè protocol. A Web browser that includes a Java processor will then automatically retrieve and execute the Java program. Two HTML tags are used to describe the applet as part of an HTML document. These are the éappleté tag and the éparamé tag. A typical sequence of instructions would be the following: éapplet codebase="http:èèwww.sun.com" code=main width=300 height=200é éparam name=name1 value="value1"é You do not have a Java enabled browser éèappleté The éappleté tag indicates the address of the Java program. The codebase parameter gives the URL Web address where the Java program will be found, 359
360 APPLETS AND WEB PROGRAMMING while the code parameter provides the name of the class. The height and width attributes tell the browser how much space to allocate to the applet. Just as users can pass information into an application using command-line arguments, applets can have information passed into them using the éparamé tags. Within an applet the values associated with parameters can be accessed using the method getparameterè è. Any code other than a éparamé tag between the beginning and end of the éappleté tag is displayed only if the program cannot be loaded. Such text can be used to provide the user with alternative information. 21.2 Security Issues Applets are designed to be loaded from a remote computer èthe serverè and then executed locally. Because most users will execute the applet without examining the code, the potential exists for malicious programmers to develop applets that would do signiæcant damage, for example erasing a hard drive. For this reason, applets are usually much more restricted than applications in the type of operations they can perform. 1. Applets are not permitted to run any local executable program. 2. Applets cannot read or write to the local computer's æle system. 3. Applets can only communicate with the server from which they originate. They are not allowed to communicate with any other host machine. 4. Applets can learn only a very restricted set of facts about the local computer. For example, applets can determine the name and version of the operating system, but not the user's name or e-mail address. In addition, dialog windows that an applet creates are normally labeled with a special text, so the user knows they were created by ajava applet and are not part of the browser application. The Java security model has been extended in Java 1.2. It is now possible to attach a digital signature to applets, so that they can be run in a less restricted environment. Discussion of this is beyond the scope of this book. 21.3 Applets and Applications All the applications created prior to this chapter that made use of graphical resources have been formed as subclasses of class JFrame. This class provided the necessary underpinnings for creating and managing windows, graphical operations, events, and the other aspects of a standalone application. A program that is intended to run on the Web has a slightly diæerent structure. Rather than subclassing from JFrame, such a program is subclassed
21.3 Applets and Applications 361 from JApplet. Just as JFrame provides the structure necessary to run a program as an application, the class JApplet provides the necessary structure and resources needed to run a program on the Web. The Swing class JApplet is a sublass of its AWT equivalent, Applet. Applet, in turn, is a subclass of Panel èsee section 13.4è and thus JApplet inherits the applet functionality of Applet and the graphical component attributes of Panel. Rather than starting execution with a static method named main, as applications do, applets start execution at a method named init, which is deæned in class Applet but can be overridden by users. The method init is one of four routines deæned in Applet that is available for overriding by users. These four can be described as follows: initè è Invoked when an applet is ærst loaded; for example, when a Web page containing the applet is ærst encountered. This method should be used for one-time initialization. This is similar to the code that would normally be found in the constructor for an application. startè è Called to begin execution of the applet. Called again each time the Web page containing the applet is exposed. This can be used for further initialization or for restarting the applet when the page on which it appears is made visible after being covered. stopè è Called when a Web page containing an applet is hidden. Applets that do extensive calculations should halt themselves when the page on which they are located becomes covered, so as to not occupy system resources. destroyè è Called when the applet is about to be terminated. Should halt the application and free any resources being used. For example, suppose a Web page containing an applet as well as several other links is loaded. The applet will ærst invoke initè è, then startè è. If the user clicks on one of the links, the Web page holding the applet is overwritten, but it is still available for the user to return to. The method stopè è will be invoked to temporarily halt the applet. When the user returns to the Web page, the method startè è, but not initè è, will once again be executed. This can happen many times before the user ænally exits altogether the page containing the applet, at which time the method destroyè è will be called. Figure 21.1 shows portions of the painting application described in Section 18.6, now written as an applet rather than as an application. In place of the main method, the applet contains an init method. The init takes the place both of main and of the constructor for the application class. Other aspects of the applet are the same. Because an applet is a subclass of Panel, events are handled in exactly the same fashion as other graphical components. Similarly, an applet repaints the window in exactly the same fashion as an application. Because an applet is a panel, it is possible to embed components and construct a complex graphical interface èsee Chapter 13è. Note, however, that the default
362 APPLETS AND WEB PROGRAMMING import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PaintApplet extends JApplet private Image image = null; private Shape currentshape = null; public void init èè. èè change our layout manager getcontentpaneèè.setlayoutènew BorderLayoutè èè; èè create panel for buttons Panel p = new Panelè è; p.setlayoutènew GridLayoutè1,3èè; p.addènew Rectangleè èè; p.addènew Ovalè èè; p.addènew Lineè èè; getconentpaneèè.addè"north", pè; MouseKeeper k = new MouseKeeperè è; addmouselistenerèkè; addmousemotionlistenerèkè; Figure 21.1 Painting program written as applet. layout manager for an Applet is a æow layout rather than the border layout that is default to applications. 21.4 Obtaining Resources Using an Applet The class JApplet provides a number of methods that can be used to load resources from the server machine. The method getimageèurlè, for example, takes a URL and retrieves the image stored in the given location. The URL must specify a æle in jpeg or gif format. The method getaudioclipèurlè similarly returns an audio object from the given location. The audioclip can subsequently be asked to play itself. A shorthand method playèurlè combines these two features. The method getcodebaseè è returns the URL for the codebase speciæed for the applet èsee the earlier discussion on HTML tagsè. Since Java programs are
21.4 Obtaining Resources Using an Applet 363 often stored in the same location as associated documents, such as gif æles, this can be useful in forming URL addresses for related resources. The method getparameterè è takes as argument a String, and returns the associated value èagain, as a stringè if the user provided a parameter of the given name using a éparamé tag. A null value is returned if no such parameter was provided. 21.4.1 Universal Resource Locators Resources, such as Java programs, gif æles, or data æles are speciæed using a universal resource locator, or URL. A URL consists of several parts, including a protocol, a host computer name, and a æle name. The following example shows these parts: ftp:èèftp.cs.orst.eduèpubèbuddèjavaèerrata.html This is the URL that points to the errata list for this book. The ærst part, ftp:, describes the protocol to be used in accessing the æle. The letters stand for File Transfer Protocol, and is one common protocol. Another common protocol is http, which stands for Hypertext Transfer Protocol. The next part, ftp.cs.orst.edu, is the name of the machine on which the æle resides. The remainder of the URL speciæes a location for a speciæc æle on this machine. File names are hierarchical. On this particular machine the directory pub is the area open to the public, the subdirectory budd is my own part of this public area, java holds æles related to the Java book, and ænally errata.html is the name of the æle containing the errata information. URLs can be created using the class URL. 1 The address is formed using a string, or using a previous URL and a string. The latter form, for example, can be used to retrieve several æles that reside in the same directory. The directory is ærst speciæed as a URL, then each æle is speciæed as a URL with the æle name added to the previous URL address. The constructor for the class URL will throw an exception called MalformedURLException if the associated object cannot be accessed across the Internet. The class URL provides a method openstream, which returns an inputstream value èsee Chapter 14è. Once you have created a URL object, you can use this method to read from the URL using the normal InputStream methods, or convert it into a Reader in order to more easily handle character values. In this way, reading from a URL is as easy as reading from a æle or any other type of input stream. The following program reads and displays the contents of a Web page. The URL for the Web page is taken from the command-line argument. import java.net.*; 1 It is important to distinguish the idea of a URL as a concept from the Java class of the same name. We will write URL in the normal font when we want to refer to a universal resource locator, and URL when we speciæcally wish to refer to the Java class.
364 APPLETS AND WEB PROGRAMMING import java.io.*; class ReadURL public static void main èstring ë ë argsè try URL address = new URLèargsë0ëè; InputStreamReader iread = new InputStreamReaderè address.openstreamè èè; BufferedReader in = new BufferedReaderèireadè; String line = in.readlineè è; while èline!= nullè System.out.printlnèlineè; line = in.readlineè è; in.closeè è; catch èmalformedurlexception eè System.out.printlnè"URL exception " + eè; catch èioexception eè System.out.printlnè"IèO exception " + eè; If you run the program, you should see the HTML commands and textual content displayed for the Web page given as argument. Since not all æles are text æles, the class URL also provides methods for reading various other formats, such as graphical images or audio æles. 21.4.2 Loading a New Web Page Applets used with Web browsers can instruct the browser to load a new page. This feature is frequently used to simulate links or buttons on a Web page, or to implement image maps. The method appletcontext.showdocumentèurlè takes a URL as argument, then instructs the Web browser to display the indicated page. 21.5 Combining Applications and Applets The class Applet pays no attention to any static methods that may be contained within the class deænition. We can use this fact to create a class that can be executed both as an applet and as an application. The key idea is that an JApplet contains a content pane is the same way as a JFrame. We can nest within the applet class an inner class that creates the JFrame necessary for
21.5 Combining Applications and Applets 365 an application. The only component of the window created for this frame will be the content pane of the applet. The main program, which is ignored by the applet, will when executed as an application create an instance of the applet. The applet can then create an instance of JFrame for the application, placing itself in the center of the window. The constructor for the JFrame executes the methods initè è and startè è required to initialize the applet. The following shows this technique applied to the painting applet described earlier: import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PaintApplet extends JApplet èè executed for applications èè ignored by applet class public static void main èstring ë ë argsè JFrame world = new PaintAppletè è.applicationè è; world.showè è; private JFrame applicationè è return new JAppletFrame èthisè; private class JAppletFrame extends JFrame public JAppletFrame èjapplet pè settitleè"paint Application"è; setsize è400, 300è; p.initè è; p.startè è; getcontentpaneèè.addè"center", pè;... èè remainder as before Trace carefully the sequence of operations being performed here and the order in which objects are created. Since the JFrame is nested within the JApplet, it is only possible to create the frame èin the method applicationè after the applet has already been created.
366 APPLETS AND WEB PROGRAMMING 21.6 Chapter Summary An applet is a Java application designed to be executed as part of a Web browser. Although much of the code for an applet is similar to that of an application, the two diæer in some signiæcant respects. Applets are created by subclassing from the class Applet, rather than from the class JFrame. Applets begin execution with the method init, rather than main. Finally, applets can be halted and restarted, as the Web browser moves to a new page and returns. Security over the Web is a major concern, and for this reason applets are restricted in the actions they can perform. For example, applets are not permitted to read or write æles from the client system. The chapter concludes by showing how it is possible to create a program that can be executed both as an application and as an applet. Study Questions 1. What is an applet? 2. What is html? 3. How canaweb page be made to point to an applet? 4. What is the purpose of the param tag? How is information described by this tag accessed within an applet? 5. What happens if a web browser cannot load and execute an applet described by an applet tag? 6. Why are applets restricted in the variety of activities they can perform? 7. What is the diæerence between the init and start methods in an applet? When will each be executed? 8. What is the function of a URL? What are the diæerent parts of a URL? 9. How can one read the contents of a æle addressed by a URL? Exercises 1. Convert the pinball game described in Chapter 7 to run as an applet, rather than as an application. 2. Convert the Tetris game described in Chapter 20 to run as an applet rather than as an application. 3. Section 18.6 presented a simple painting program. Convert this program to run as an applet, rather than as an application.