You use HTML (the hypertext markup language) to describe the layout of a web page. HTML is simply a vehicle to indicate elements of a hypertext page. For example, <title> indicates the title of the page, and any text that follows this tag becomes the title of the page. You indicate the end of the title with the </title> tag. (This is one of the general rules for tags: a slash followed by the name of the element indicates the end of the element.) The basic idea of how to use applets in a web page is simple: the HTML page must tell the browser which applets to load and then where to put each applet on the web page. As you might expect, the tag needed to use an applet must tell the browser the following:
The browser then retrieves the class files from the Internet (or from a directory on the user's machine) and automatically runs the applet, using an external Java runtime environment or its built-in Java virtual machine. In addition to the applet itself, the web page can contain all the other HTML elements you have seen in use on web pages: multiple fonts, bulleted lists, graphics, links, and so on. Applets are just one part of the hypertext page. It is always worth keeping in mind that the Java programming language is not a tool for designing HTML pages; it is a tool for bringing them to life. This is not to say that the GUI design elements in a Java applet are not important, but that they must work with (and, in fact, are subservient to) the underlying HTML design of the web page. NOTE
When applets were first developed, you had to use Sun's HotJava browser to view web pages that contained applets. Naturally, few users were willing to use a separate browser just to enjoy a new web feature. Java applets became really popular when Netscape included a Java virtual machine in its Navigator browser. Microsoft Internet Explorer soon followed suit. Unfortunately, two problems happened. Netscape didn't keep up with more modern versions of Java, and Microsoft vacillated between reluctantly supporting outdated Java versions and dropping Java support altogether. To overcome this problem, Sun released a tool called the "Java Plug-in". Using the various extension mechanisms of Internet Explorer or Navigator, it seamlessly plugs in to both Netscape and Internet Explorer and allows both browsers to execute Java applets by using an external Java runtime environment that Sun supplies. By keeping the Plug-in up-to-date, you can always take advantage of the latest and greatest features of Java. NOTE
Admittedly, if you are designing web pages for a wide audience, it is probably unreasonable to ask the visitors to your web page to install the Java Plug-in, which is a fairly hefty (if one-time) download. Before turning to applets, you should check whether you can just use HTML forms, JavaScript, and animated GIF files to implement the client user interface. Then place the intelligence on the server, preferably with Java-based servlets and server pages. On the other hand, if you roll out a very sophisticated Java program, you should ask yourself whether there is any benefit from using the web browser as a delivery vehicle. If not, then you can simply deliver Java applications that your users run on their local machines. You still have all the benefits of Java, such as platform independence, security management, and easy database and network access. Of course, there are advantages to web deployment. For a user, it is often easier to locate an application on the Web than on the local file system. (This is particularly true for applications that aren't used every day.) For an administrator, it is easier to maintain and update an application on the web server than to push out bug fixes and improvements to lots of client desktops. Thus, among the most successful Java programs are corporate intranet applications that interface with corporate information systems. For example, many companies have put expense reimbursement calculators, benefit tracking tools, schedule and vacation planners, purchase order requests, and so on, on their corporate intranet. These programs are relatively small, need to interface with databases, need more flexibility than web forms can provide, and need to be customized to the operations of a particular company. Applets and the Java Web Start mechanisms are excellent delivery technologies for these programs. Because the user population is constrained, it is less of a problem to manage the installation of the Java run time. We start out with applets, both for the sake of tradition and because understanding applets gives you a head start with the Java Web Start technology. A Simple AppletFor tradition's sake, let's write a NotHelloWorld program as an applet. Before we do that, we want to point out that, from a programming point of view, an applet isn't very strange. An applet is simply a Java class that extends the java.applet.Applet class. Note that although the java.applet package is not part of the AWT package, an applet is an AWT component, as the inheritance chain shown in Figure 10-1 illustrates. In this book, we will use Swing to implement applets. All of our applets will extend the JApplet class, the superclass for Swing applets. As you can see in Figure 10-1, JApplet is an immediate subclass of the ordinary Applet class. Figure 10-1. Applet inheritance hierarchyNOTE
Example 10-1 shows the code for an applet version of "Not Hello World". Notice how similar this is to the corresponding program from Chapter 7. However, because the applet lives inside a web page, there is no need to specify a method for exiting the applet. Example 10-1. NotHelloWorldApplet.java1 ./* 2. The following HTML tags are required to display this applet in a browser: 3. <applet code="NotHelloWorldApplet.class" width="300" height="100"> 4. </applet> 5. */ 6. 7. import javax.swing.*; 8. 9. public class NotHelloWorldApplet extends JApplet 10. { 11. public void init() 12. { 13. JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER); 14. add(label); 15. } 16. } Applet ViewingTo execute the applet, you carry out two steps:
It is customary (but not necessary) to give the HTML file the same name as that of the applet class inside. So, following this tradition, we call the file NotHelloWorldApplet.html. Here are the contents of the file: <applet code="NotHelloWorldApplet.class" width="300" height="300"> </applet> Before you view the applet in a browser, it is a good idea to test it in the applet viewer program that is a part of the JDK. To use the applet viewer in our example, enter appletviewer NotHelloWorldApplet.html at the command line. The command-line argument for the applet viewer program is the name of the HTML file, not the class file. Figure 10-2 shows the applet viewer displaying this applet. Figure 10-2. Viewing an applet in the applet viewerTIP
TIP
The applet viewer is good for the first stage of testing, but at some point you need to run your applets in a browser to see them in the same way a user might use them. In particular, the applet viewer program shows you only the applet, not the surrounding HTML text. If an HTML file contains multiple applet tags, the applet viewer pops up multiple windows. To properly view the applet, you need a Java 2-enabled browser. After installing and configuring the Java Plug-in, simply load the HTML file into the browser (see Figure 10-3). If the applet doesn't show up, your browser probably uses its built-in virtual machine, and you need to configure it to use the Java Plug-in instead. Figure 10-3. Viewing an applet in a browserTIP
NOTE
Application Conversion to AppletsIt is easy to convert a graphical Java application (that is, an application that uses the AWT and that you can start with the java program launcher) into an applet that you can embed in a web page. Essentially, all of the user interface code can stay the same. Here are the specific steps for converting an application to an applet.
NOTE
As an example of this transformation, we will change the calculator application from Chapter 9 into an applet. In Figure 10-4, you can see how it looks, sitting inside a web page. Figure 10-4. A calculator appletExample 10-2 shows the HTML page. Note that there is some text in addition to the applet tags. Example 10-2. Calculator.html1. <html> 2. <head><title>A Calculator</title></head> 3. <body> 4. <p>Here is a calculator, just in case you can't find yours.</p> 5. <applet code="CalculatorApplet.class" width="180" height="180"> 6. </applet> 7. </body> 8. </html> Example 10-3 is the code for the applet. We introduced a subclass of JApplet, placed the initialization code into the init method, and removed the calls to setTitle, setSize, setDefaultCloseOperation, and setVisible. The CalculatorPanel class is taken from Chapter 9, and its code is omitted. Example 10-3. CalculatorApplet.java1. import java.awt.*; 2. import javax.swing.*; 3. 4. public class CalculatorApplet extends JApplet 5. { 6. public void init() 7. { 8. CalculatorPanel panel = new CalculatorPanel(); 9. add(panel); 10. } 11. } java.applet.Applet 1.0
Life Cycle of an AppletFour methods in the Applet class give you the framework on which you build any serious applet: init, start, stop, and destroy. What follows is a short description of these methods, occasions when these methods are called, and the code you should place into them.
java.applet.Applet 1.0
Security BasicsBecause applets are designed to be loaded from a remote site and then executed locally, security becomes vital. If a user enables Java in the browser, the browser will download all the applet code on the web page and execute it immediately. The user never gets a chance to confirm or to stop individual applets from running. For this reason, applets (unlike applications) are restricted in what they can do. The applet security manager throws a SecurityException whenever an applet attempts to violate one of the access rules. What can applets do on all platforms? They can show images and play sounds, get keystrokes and mouse clicks from the user, and send user input back to the host from which they were loaded. That is enough functionality to show facts and figures or to get user input for placing an order. The restricted execution environment for applets is often called the "sandbox." Applets playing in the "sandbox" cannot alter the user's system or spy on it. In this chapter, we look only at applets that run inside the sandbox. In particular, when running in the sandbox,
All this is possible only because applets are executed by the Java virtual machine and not directly by the CPU on the user's computer. Because the virtual machine checks all critical instructions and program areas, a hostile (or poorly written) applet will almost certainly not be able to crash the computer, overwrite system memory, or change the privileges granted by the operating system. These restrictions are too strong for some situations. For example, on a corporate intranet, you can certainly imagine an applet wanting to access local files. To allow for different levels of security under different situations, you can use signed applets. A signed applet carries with it a certificate that indicates the identity of the signer. Cryptographic techniques ensure that such a certificate cannot be forged. If you trust the signer, you can choose to give the applet additional rights. (We cover code signing in Volume 2.) The point is that if you trust the signer of the applet, you can tell the browser to give the applet more privileges. You can, for example, give applets in your corporate intranet a higher level of trust than those from www.cracker.com. The configurable Java security model allows the continuum of privilege levels you need. You can give completely trusted applets the same privilege levels as local applications. Programs from vendors that are known to be somewhat flaky can be given access to some, but not all, privileges. Unknown applets can be restricted to the sandbox. NOTE
To sum up, Java has three separate mechanisms for enforcing security:
NOTE
Pop-Up Windows in AppletsAn applet sits embedded in a web page, in a frame whose width is given by the width and height attributes in the applet tag. This can be quite limiting. Many programmers wonder whether they can have a pop-up window to make better use of the available space. It is indeed possible to create a pop-up frame. Here is a simple applet with a single button labeled Calculator. When you click on the button, a calculator pops up in a separate window. The pop-up is easy to do. Simply use a JFrame, but don't call setDefaultCloseOperation. frame = new CalculatorFrame(); frame.setTitle("Calculator"); frame.setSize(200, 200); When the user clicks the button, toggle the frame so that it is shown if it isn't visible and hidden if it is. When you click on the calculator button, the dialog box pops up and floats over the web page. When you click on the button again, the calculator goes away. JButton calcButton = new JButton("Calculator"); calcButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frame.setVisible(!frame.isVisible()); } }); There is, however, an issue that you need to consider before you put this applet on your web page. To see how the calculator looks to a potential user, load the web page from a browser, not the applet viewer. The calculator will be surrounded by a border with a warning message (see Figure 10-5). Figure 10-5. A window that pops up over a browserIn early browser versions, that message was very ominous: "Untrusted Java Applet Window". Every successive version of the JDK watered down the warning a bit "Unauthenticated Java Applet Window", or "Warning: Java Applet Window". Now it is simply "Java Applet Window". This message is a security feature of all web browsers. The browser wants to make sure that your applet does not launch a window that the user might mistake for a local application. The fear is that an unsuspecting user could visit a web page, which automatically launches the applets on it, and mistakenly type in a password or credit card number, which the applet could send back to its host. To avoid any possibility of shenanigans like this, all pop-up windows launched by an applet bear a warning label. You can configure the Java Plug-in to omit the warning message for pop-up windows that are spawned by signed applets. Example 10-4 shows the code for the PopupCalculatorApplet class. Example 10-4. PopupCalculatorApplet.java1. import java.awt.*; 2. import java.awt.event.*; 3. import javax.swing.*; 4. 5. public class PopupCalculatorApplet extends JApplet 6. { 7. public void init() 8. { 9. // create a frame with a calculator panel 10. 11. final JFrame frame = new JFrame(); 12. frame.setTitle("Calculator"); 13. frame.setSize(200, 200); 14. frame.add(new CalculatorPanel()); 15. 16. // add a button that pops up or hides the calculator 17. 18. JButton calcButton = new JButton("Calculator"); 19. add(calcButton); 20. 21. calcButton.addActionListener(new 22. ActionListener() 23. { 24. public void actionPerformed(ActionEvent event) 25. { 26. frame.setVisible(!frame.isVisible()); 27. } 28. }); 29. } 30. } |