How To Write A Program For The Web In Java (Java)



Similar documents
The Basic Java Applet and JApplet

CS506 Web Design and Development Solved Online Quiz No. 01

Computing Concepts with Java Essentials

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Introduction to Java Applets (Deitel chapter 3)

Java Application Developer Certificate Program Competencies

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

CSC 551: Web Programming. Spring 2004

WEEK 2 DAY 14. Writing Java Applets and Java Web Start Applications

There are some important differences between an applet and a standalone Java application, including the following:

Building a Multi-Threaded Web Server

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Java applets. SwIG Jing He

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Fundamentals of Java Programming

Syllabus for CS 134 Java Programming

Division of Informatics, University of Edinburgh

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

16.1 DataFlavor DataFlavor Methods. Variables

Tutorial Reference Manual. Java WireFusion 4.1

LabVIEW Internet Toolkit User Guide

Serving tn5250j in Web Documents from the HTTP Server for iseries

An Overview of Java. overview-1

Ad Hoc Reporting. Usage and Customization

Tableau Server Trusted Authentication

OCS Training Workshop LAB13. Ethernet FTP and HTTP servers

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

For Introduction to Java Programming, 5E By Y. Daniel Liang

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Hypercosm. Studio.

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Essentials of the Java(TM) Programming Language, Part 1

The MultiHttpServer A Parallel Pull Engine

IT6503 WEB PROGRAMMING. Unit-I

Lesson: All About Sockets

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Using The HomeVision Web Server

DC60 JAVA AND WEB PROGRAMMING JUNE b. Explain the meaning of the following statement public static void main (string args [ ] )

TIBCO Spotfire Automation Services 6.5. User s Manual

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

Extending Desktop Applications to the Web

Using IIS and UltraDev Locally page 1

Using Adobe Dreamweaver CS4 (10.0)

Cache Configuration Reference

Windows PowerShell Essentials

How to Develop Accessible Linux Applications

Terms and Definitions for CMS Administrators, Architects, and Developers

BlueJ Teamwork Tutorial

Developing Web Views for VMware vcenter Orchestrator

Mouse Event Handling (cont.)

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview

T320 E-business technologies: foundations and practice

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

CS 335 Lecture 06 Java Programming GUI and Swing

My IC Customizer: Descriptors of Skins and Webapps for third party User Guide

Apple Applications > Safari

Oracle Forms Services Secure Web.Show_Document() calls to Oracle Reports Server 6i

How To Use A Sas Server On A Java Computer Or A Java.Net Computer (Sas) On A Microsoft Microsoft Server (Sasa) On An Ipo (Sauge) Or A Microsas (Sask

Java Interview Questions and Answers

ICT 6012: Web Programming

Specify the location of an HTML control stored in the application repository. See Using the XPath search method, page 2.

Enhanced Connector Applications SupportPac VP01 for IBM WebSphere Business Events 3.0.0

JAVA. EXAMPLES IN A NUTSHELL. O'REILLY 4 Beijing Cambridge Farnham Koln Paris Sebastopol Taipei Tokyo. Third Edition.

Copyright 2008 The Pragmatic Programmers, LLC.

understand how image maps can enhance a design and make a site more interactive know how to create an image map easily with Dreamweaver

Advanced Network Programming Lab using Java. Angelos Stavrou

AP Computer Science Java Subset

Programming with Java GUI components

Online Advertising Creative Specifications

Voluntary Product Accessibility Report

BCA 421- Java. Tilak Maharashtra University. Bachelor of Computer Applications (BCA) 1. The Genesis of Java

11. Applets, normal window applications, packaging and sharing your work

Guide to Analyzing Feedback from Web Trends

Web Design Specialist

PaperlessPrinter. Version 3.0. User s Manual

Java History. Java History (cont'd)

SHARP Digital Signage Software Pro PN-SS05 OPERATION MANUAL

End User Guide The guide for /ftp account owner

Adobe Acrobat 9 Pro Accessibility Guide: Creating Accessible PDF from Microsoft Word

Java (12 Weeks) Introduction to Java Programming Language

Applets, RMI, JDBC Exam Review

Specialized Programme on Web Application Development using Open Source Tools

Adobe Dreamweaver CC 14 Tutorial

GUI Components: Part 2

Server & Workstation Installation of Client Profiles for Windows

SETTING UP A WEATHER DATA WEB PAGE Application Note 26

Remote Access and Control of the. Programmer/Controller. Version 1.0 9/07/05

Cloud Portal for imagerunner ADVANCE

Packaging and Deploying Java Projects in Forte

Troubleshooting AVAYA Meeting Exchange

Tableau Server Trusted Authentication

CiviCRM for The Giving Circle. Bulk Mailing Tips & Tricks

Xtreeme Search Engine Studio Help Xtreeme

PHP Debugging. Draft: March 19, Christopher Vickery

13 File Output and Input

Transcription:

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.