• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
8
0
0

Loading.... (view fulltext now)

Full text

(1)

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. Thecodebase parameter gives the URL Web address where the Java program will be found,

(2)

while thecode parameter provides the name of the class. Theheightandwidth 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 methodgetParameter( ).

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 a Java 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 classJFrame. 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 fromJFrame, such a program is subclassed

(3)

fromJApplet. Just asJFrameprovides 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 appli- cations do, applets start execution at a method named init, which is de ned in class Applet but can be overridden by users. The method initis one of four routines de ned in Appletthat 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 invokeinit( ), thenstart( ). 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 methodstop( )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 methoddestroy( ) will be called.

Figure 21.1 shows portions of the painting application described in Sec- tion 18.6, now written as an applet rather than as an application. In place of the mainmethod, the applet contains aninit method. The inittakes the place both ofmainand 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

(4)

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);

}. .. }

Figure21.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 injpegorgifformat. The methodgetAudioClip(URL)similarly returns an audio object from the given location. TheaudioClipcan 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

(5)

often stored in the same location as associated documents, such asgif 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 ResourceLocators

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 forFile

TransferProtocol, and is one common protocol. Another common protocol is http, which stands forHypertextTransferProtocol. 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 subdirectorybuddis my own part of this public area,javaholds les related to the Java book, and nally errata.htmlis 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 previousURLand 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 URLprovides a method openStream, which returns aninputStream value (see Chapter 14). Once you have created aURLobject, you can use this method to read from the URL using the normalInputStreammethods, 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.*;

1It 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, andURL when we speci cally wish to refer to the Java class.

(6)

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 classURLalso provides methods for reading various other formats, such as graphical images or audio les.

21.4.2 Loading a NewWeb 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 methodappletContext.showDocument(URL)takes a URL as argument, then instructs the Web browser to display the indicated page.

21.5

Combining Applications and Applets

The classAppletpays 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

(7)

an application. The only component of the window created for this frame will be the content pane of the applet. Themainprogram, 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 JFramefor the application, placing itself in the center of the window. The constructor for theJFrameexecutes the methodsinit( )andstart( )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 theJFrameis nested within theJApplet, it is only possible to create the frame (in the methodapplication) after the applet has already been created.

(8)

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 classApplet, rather than from the classJFrame. Applets begin execution with the methodinit, rather thanmain. 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 can a web page be made to point to an applet?

4. What is the purpose of theparamtag? 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 anapplet 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.

References

Related documents

The runtime security data of the Java Card RE, like, for instance, the AIDs used to identify the installed applets, the currently selected applet, the current context of execution

Based on this, this paper mainly studies the multirobot autonomous navigation problem in power stations of smart microgrids, and multimobile robots are used to complete the

Given the restricted use of e-signatures to include internal use only and the requirement that all users must be authenticated to the Authority domain for an e-signature to be

In the current work, the green and orange illumination sources were used for both signals of two different wavelength measurements obtained from the DC and AC components,

Doctor of Philosophy in Higher Education Administration and Organizational Development, Kent State University, Kent, Ohio, 2001 Master of Science in Secondary Education,

(2004) Comparison of MPEG-7 audio spectrum projection features and MFCC applied to speaker recognition, sound classification and audio segmentation, In : Proceedings of the

In fact, Clifford could respond affirming that, even if there are beneficial consequences following beliefs upon insufficient evidence, that proves neither that we are fulfilling

A 3-parameter cubic equation of state NEoS associated with the Mathias-Copeman alpha function, and with vdW classical mixing rules was used for the modelling calculations, and leads