Java Applets

 <  Day Day Up  >  


Whereas both Microsoft's ActiveX and Netscape's plug-ins are platform and browser specific, Sun Microsystems' Java technology (http://java.sun.com) aimed to provide a platform-neutral development language, allowing programs to be written once and deployed on any machine, browser, or operating system that supports the Java virtual machine (JVM). Java uses small Java programs, called applets , that were first introduced by Sun's HotJava browser. Today, applets are supported by most Web browsers, including Netscape Navigator and Microsoft Internet Explorer. Of course, the nirvana of perfect cross-platform development never really materialized. Many versions of the Windows operating system do not ship with Java virtual machines and the technology never really took off in public Web sites. However, they are still used and Java applets continue to play an important role even in client-side development, particularly within controlled environments such as intranets .

Applets are written in the Java language and compiled to a machine-independent byte-code, which is downloaded automatically to the Java-capable browser and run within the browser environment. But even with a fast processor, the end system might appear to run the byte-code slowly compared to a natively compiled application because the byte code must be interpreted by the Java Virtual Machine. Even with recent Just-In-Time (JIT) compilers in newer browsers, Java often doesn't deliver performance equal to natively compiled applications upon startup. Once running, Java applets and applications perform well. However, even if compilation weren't an issue, current Java applets generally aren't persistent; they may have to be downloaded again in the future. Java-enabled browsers act like thin-client applications because they add code only when they need it. In this sense, the browser doesn't become bloated with added features, but expands and contracts upon use.

Security in Java has been considered from the outset. Because programs are downloaded and run automatically, a malicious program could be downloaded and run without the user being able to stop it. Under the first implementation of the technology, Java applets had little access to resources outside the browser's environment. Within Web pages, applets can't write to local disks or perform other harmful functions. This framework has been referred to as the Java sandbox . Developers who want to provide Java functions outside of the sandbox must write Java applications, which run as separate applications from browsers. Other Internet programming technologies (for example, ActiveX) provide little or no safety from damaging programs.

Oddly, Java developers often want to add just these types of insecure features, as well as such powerful features as persistence and inter-object communication. In fact, under new browsers, extended access can be requested for signed Java applets. (A signed applet enables users to determine who authored its code, and to accept or reject the applet accordingly .) Java applets can securely request limited disk access, limited disk access and network usage, limited disk read access and unlimited disk write access, and unrestricted access. Users downloading an applet that is requesting any enhanced privileges are presented with a dialog box that outlines the requested access and presents the applet's credentials in the form of its digital signature. The user then can approve or reject the applet's request. If the user doesn't approve the request, the applet can continue to run, but it can't perform the denied actions.

Java code looks very much like C++. The following code fragment shows a simple example of a Java applet:

 import java.applet.Applet; import java.awt.Graphics;     public class helloworld extends Applet  {     public void paint(Graphics g)      {         g.drawString("Hello World", 50, 25);      } } 

You can save this previous example into a file named helloworld.java and then send the code through a Java compiler (such as JavaSoft's javac) to produce a class file called helloworld.class, which can be used on a Web page to display the phrase "Hello World." You can use an <applet> tag to add a Java applet to a Web page. As with the <embed> tag, you must indicate the object to add. In this case, use the code attribute to indicate the URL of the Java class file to load. Because this is an included object, the height and width attributes should also be set. The following example includes the HelloWorld applet in a Web page. Figure 15-5 shows the rendering of the Java example under Netscape 4 with Java turned on and Java turned off.

click to expand
Figure 15-5: Java example under Netscape 4 with Java turned on and off
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Java Hello World  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   </head>   <body>   <h1 align="center">  Java Applet Demo  </h1>   <hr />   <applet code="helloworld.class"   height="50" width="175">   <h1>  Hello World for you non-Java-aware browsers  </h1>   </applet>   </body>   </html>  

In the preceding code example, between <applet> and </applet> is an alternative rendering for browsers that don't support Java or the applet element, or that have Java support disabled.

<applet> Syntax

Because Java applets are included objects, just like Netscape plug-ins, the syntax for the applet element is similar to the embed element, particularly for things such as alignment and sizing. The complete syntax for <applet> is shown in the element reference in Appendix A.

The most important attribute for the applet element probably is code , which is set to the URL of the Java class to load into the page. The codebase attribute can be set to the URL of the directory that contains the Java classes; otherwise , the current document's URL is used for any relative URLs.

Because Java applets are rectangular, embedded objects similar to images or plug-ins, an <applet> tag has many of the same attributes as images and plug-ins, including align , height , width , hspace , and vspace .

The archive attribute can be used to include many classes into a single archive file, which then can be downloaded to the local disk. The file specified by the archive attribute can be a compressed ZIP file (.zip) or a Java Archive (.jar), which can be made with a JAR packaging utility. For example,

  <applet archive="bunchofclasses.zip"   code="sampleApp.class"   width="560"   height="270">   </applet>  

downloads all the classes in bunchofclasses.zip. After the file is downloaded, the code attribute is examined and the archive is checked to see whether sampleApp.class exists there. If not, it is fetched from the network. Due to the expense of fetching many class files by using HTTP, ideally , you should attempt to archive all potentially used classes and send them simultaneously . You also can derive some caching benefit by using the archive attribute because it keeps class files in the user's cache or a temporary directory. According to the HTML specification, the archive attribute can take a comma-separated list of archive files.

Passing Data to Java Applets

Unlike plug-ins, Java applets don't use special attributes to pass data. Instead, like ActiveX control's syntax, they use a different tag called <param> , which is enclosed within an <applet> tag, as the way to pass on information. You could extend the HelloWorld applet to allow the message output to be modified by using the <param> tag to pass in a message, as shown here:

  <applet code="helloworld.class" width="50" height="175">   <param name="Message" value="Hello World in Java!" />   <h1>  Hello World for you non-Java-aware browsers  </h1>   </applet>  

The following is the basic transitional XHTML syntax for <param> . Note that it is the same for Java applets and ActiveX controls:

  <param name  ="  Object property name  "  value  ="  Value to pass in with object name  "  valuetype  ="DATA  REF  OBJECT"  type  ="  MIME Type  "  id  ="  document-wide unique id  "  />  

The name attribute for <param> is used to specify the name of the object property that is being set; in the preceding example, the name is "Message." If you are using a pre-made Java applet, the various property names should be specified in the documentation for the applet. The actual value to be assigned to the property is set by the value attribute. The valuetype attribute specifies the meaning of the value attribute. The data passed to an attribute typically takes the form of a string. Setting the valuetype attribute to data results in the default action. Setting valuetype to ref indicates that the data assigned to the value attribute is a URL that references an external file to load for the attribute. The last value for valuetype is object , which indicates that value is set to the name of an applet or object located somewhere else within the document. The data in the applet or object can be referenced to allow objects to "talk" to each other.

The param elements for a particular Java applet occur within the <applet> tag; a Java applet can have many param elements. The applet element also can enclose regular XHTML markup and other textual content that provides an alternative rendering for non-Java- capable browsers. When alternative content is found within the <applet> , the <param> tags should be placed before the other content. Note that you also can set the alt attribute for the applet element to provide a short description. Authors should use the text contained within the element as the alternative text, and not the alt attribute.

Java Applets and Scripting

Java applets can control scripts in a Web page. Supposedly, the inclusion of the mayscript attribute in an <applet> tag permits the applet to access JavaScript. When dealing with applets retrieved from other sources, you can use the mayscript attribute to prevent the applet from accessing JavaScript without the user's knowledge. If an applet attempts to access JavaScript when this attribute has not been specified, a run-time exception should occur. In practice, however, it appears that browsers do not necessarily care about the absence of mayscript .

Probably more interesting for page designers is the fact that scripts can control or even modify Java applets that are embedded in a page. For the applet to be accessed, it should be named using the name attribute as well as the id attribute. Providing a unique name for the applet allows scripts to access the applet and its public interfaces. The name also can be used by other applets to allow the applets to communicate with each other. JavaScript in Netscape 3 and above, as well as in Internet Explorer 4 and above, allows access to the applets in a page via the applets[ ] collection, which is a property of the document object. When an applet is named, it can be accessed through JavaScript as document. appletname , such as document.myApplet , or through the array of applets in the document such as document.applets[0] or document.applets["myApplet"] . If the Java applet has public properties exposed, they can be modified from a script in a Web page. The following simple Java code takes the "Hello World" example from earlier in the chapter and expands it with a setMessage method, which can be used to change the message displayed in the applet:

 import java.applet.Applet; import java.awt.Graphics; public class newhelloworld extends Applet  {     String theMessage;         public void init()      {        theMessage = new String("Hello World");      }     public void paint(Graphics g)      {         g.drawString(theMessage, 50, 25);      }     public void setMessage(String message)      {        theMessage = message;        repaint();      } } 

If this Java code is compiled into a class file as explained earlier, it can be included in a Web page and accessed via JavaScript, as shown next . The following example markup shows how a form could be used to collect data from the user and update the applet in real time:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Java and Scripting Demo  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   <script type="text/javascript">   <!--   function setMessage()   {   var message = document.TestForm.NewMessage.value;   document.NewHello.setMessage(message);   }   //-->   </script>   </head>   <body>   <h1 align="center">  Java and Scripting Demo  </h1>   <hr />   <applet code="newhelloworld.class"   name="NewHello"   height="50" width="175">   <h1>  You need Java for this example.  </h1>   </applet>   <br /><br />   <form action="#" name="TestForm" id="TestForm">   <input type="text" size="15" maxlength="15" name="NewMessage" />   <input type="button" value="Set Message" onclick="setMessage()" />   </form>   </body>   </html>  

<object> Syntax for Java Applets

The strict variants of HTML and XHTML indicate that the applet element has been deprecated and that object should be used instead. The following is the most basic XHTML syntax for inserting an object, such as a Java applet:

  <object classid=  "  URL of object to include  "  height=  "  pixels or percentage  "  width=  "  pixels or percentage   "  >  Parameters and alternative text   </object>  

For the complete <object> syntax, see the element reference in Appendix A.

Notice that the classid attribute is used to specify the URL of the object to include. In the case of Java applets, you should use java: . For ActiveX controls, use clsid : . The following example rewrites the first simple Java applet example to use <object> and to work under strict XHTML:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">   <html xmlns="http://www.w3.org/1999/xhtml" lang="en">   <head>   <title>  Java Hello World  </title>   <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />   </head>   <body>   <h1>  Java Applet Demo  </h1>   <hr />   <div>   <object classid="java:helloworld.class"   height="50" width="175">   <h1>  Hello World for you non-Java-aware browsers  </h1>   </object>   </div>   </body>   </html>  

Because of the fragmentation of the Java community, Sun has made some attempts to bring together the syntax of Java applets using a Java plug-in. The specific syntax for this plug-in under Netscape and Internet Explorer includes both <object> and <embed> forms. Readers interested in this syntax for applet inclusion should go straight to Sun's Java support site for the latest syntax (http://java.sun.com) because the syntax continues to change.



 <  Day Day Up  >  


HTML & XHTML
HTML & XHTML: The Complete Reference (Osborne Complete Reference Series)
ISBN: 007222942X
EAN: 2147483647
Year: 2003
Pages: 252
Authors: Thomas Powell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net