Manipulating URLs

The Internet offers many protocols. The Hypertext Transfer Protocol (HTTP), which forms the basis of the World Wide Web, uses URIs (Uniform Resource Identifiers) to identify data on the Internet. URIs that specify the locations of documents are called URLs (Uniform Resource Locators). Common URLs refer to files or directories and can reference objects that perform complex tasks, such as database lookups and Internet searches. If you know the HTTP URL of a publicly available HTML document anywhere on the Web, you can access it through HTTP.

Java makes it easy to manipulate URLs. When you use a URL that refers to the exact location of a resource (e.g., a Web page) as an argument to the showDocument method of interface AppletContext, the browser in which the applet is executing will display that resource. The applet in Fig. 24.1 and Fig. 24.2 demonstrates simple networking capabilities. It enables the user to select a Web page from a JList and causes the browser to display the corresponding page. In this example, the networking is performed by the browser.

Figure 24.1. HTML document to load SiteSelector applet.

2 Site Selector 3 4 "SiteSelector.class" width = "300" height = "75"> 5 "title0" value = "Java Home Page"> 6 "location0" value = ""> 7 "title1" value = "Deitel"> 8 "location1" value = ""> 9 "title2" value = "JGuru"> 10 "location2" value = ""> 11 "title3" value = "JavaWorld"> 12 "location3" value = ""> 13 14 15

Figure 24.2. Loading a document from a URL into a browser.

(This item is displayed on pages 1110 - 1112 in the print version)

 1 // Fig. 24.2:
 2 // This program loads a document from a URL.
 3 import;
 4 import; 
 5 import java.util.HashMap;
 6 import java.util.ArrayList;
 7 import java.awt.BorderLayout;
 8 import java.applet.AppletContext; 
 9 import javax.swing.JApplet;
10 import javax.swing.JLabel;
11 import javax.swing.JList;
12 import javax.swing.JScrollPane;
13 import javax.swing.event.ListSelectionEvent;
14 import javax.swing.event.ListSelectionListener;
16 public class SiteSelector extends JApplet
17 {
18 private HashMap< Object, URL > sites; // site names and URLs
19 private ArrayList< String > siteNames; // site names
20 private JList siteChooser; // list of sites to choose from
22 // read HTML parameters and set up GUI
23 public void init()
24 {
25 sites = new HashMap< Object, URL >(); // create HashMap
26 siteNames = new ArrayList< String >(); // create ArrayList
28 // obtain parameters from HTML document
29 getSitesFromHTMLParameters();
31 // create GUI components and layout interface
32 add( new JLabel( "Choose a site to browse" ), BorderLayout.NORTH );
34 siteChooser = new JList( siteNames.toArray() ); // populate JList
35 siteChooser.addListSelectionListener(
36 new ListSelectionListener() // anonymous inner class
37 {
38 // go to site user selected
39 public void valueChanged( ListSelectionEvent event )
40 {
41 // get selected site name
42 Object object = siteChooser.getSelectedValue();
44 // use site name to locate corresponding URL
45 URL newDocument = sites.get( object ); 
47 // get applet container 
48 AppletContext browser = getAppletContext();
50 // tell applet container to change pages
51 browser.showDocument( newDocument ); 
52 } // end method valueChanged
53 } // end anonymous inner class
54 ); // end call to addListSelectionListener
56 add( new JScrollPane( siteChooser ), BorderLayout.CENTER );
57 } // end method init
59 // obtain parameters from HTML document
60 private void getSitesFromHTMLParameters()
61 {
62 String title; // site title
63 String location; // location of site
64 URL url; // URL of location
65 int counter = 0; // count number of sites
67 title = getParameter( "title" + counter ); // get first site title
69 // loop until no more parameters in HTML document
70 while ( title != null )
71 {
72 // obtain site location
73 location = getParameter( "location" + counter );
75 try // place title/URL in HashMap and title in ArrayList
76 {
77 url = new URL( location ); // convert location to URL
78 sites.put( title, url ); // put title/URL in HashMap
79 siteNames.add( title ); // put title in ArrayList
80 } // end try
81 catch ( MalformedURLException urlException )
82 {
83 urlException.printStackTrace();
84 } // end catch
86 counter++;
87 title = getParameter( "title" + counter ); // get next site title
88 } // end while
89 } // end method getSitesFromHTMLParameters
90 } // end class SiteSelector

This applet takes advantage of applet parameters specified in the HTML document that invokes the applet. When browsing the World Wide Web, you will often come across applets that are in the public domainyou can use them free of charge on your own Web pages (normally in exchange for crediting the applet's creator). Many applets can be customized via parameters supplied from the HTML file that invokes the applet. For example, Fig. 24.1 contains the HTML that invokes the applet SiteSelector in Fig. 24.2.

The HTML document contains eight parameters specified with the param tagthese lines must appear between the starting and ending applet tags. The applet can read these values and use them to customize itself. Any number of param tags can appear between the starting and ending applet tags. Each parameter has a name and a value. Applet method getParameter retrieves the value associated with a specific parameter name and returns it as a string. The argument passed to getParameter is a string containing the name of the parameter in the param element. In this example, parameters represent the title and location of each Web site the user can select. Parameters specified for this applet are named title#, where the value of # starts at 0 and increments by 1 for each new title. Each title should have a corresponding location parameter of the form location#, where the value of # starts at 0 and increments by 1 for each new location. The statement

 String title = getParameter( "title0" );


gets the value associated with parameter "title0" and assigns it to reference title. If there is no param tag containing the specified parameter, getParameter returns null.

The applet (Fig. 24.2) obtains from the HTML document (Fig. 24.1) the choices that will be displayed in the applet's JList. Class SiteSelector uses a HashMap (package java.util) to store the Web site names and URLs. In this example, the key is the string in the JList that represents the Web site name, and the value is a URL object that stores the location of the Web site to display in the browser.

Class SiteSelector also contains an ArrayList (package java.util) in which the site names are placed so that they can be used to initialize the JList (one version of the JList constructor receives an array of Objects which is returned by ArrayList's toArray method). An ArrayList is a dynamically resizable array of references. Class ArrayList provides method add to add a new element to the end of the ArrayList. (We provide discussions of classes ArrayList and HashMap in Chapter 19.)

Lines 2526 in the applet's init method (lines 2357) create a HashMap object and an ArrayList object. Line 29 calls our utility method getSitesFromHTMLParameters (declared at lines 6089) to obtain the HTML parameters from the HTML document that invoked the applet.

In method getSitesFromHTMLParameters, line 67 uses Applet method getParameter to obtain a Web site title. If the title is not null, the loop at lines 7088 begins executing. Line 73 uses Applet method getParameter to obtain the Web site location. Line 77 uses the location as the value of a new URL object. The URL constructor determines whether its argument represents a valid URL. If not, the URL constructor throws a MalformedURLException. Note that the URL constructor must be called in a TRy block. If the URL constructor generates a MalformedURLException, the call to printStackTrace (line 83) causes the program to output a stack trace to the Java console. On Windows machines, the Java console can be viewed by right clicking the Java icon in the notification area of the taskbar. Then the program attempts to obtain the next Web site title. The program does not add the site for the invalid URL to the HashMap, so the title will not be displayed in the JList.

For a proper URL, line 78 places the title and URL into the HashMap, and line 79 adds the title to the ArrayList. Line 87 gets the next title from the HTML document. When the call to getParameter at line 87 returns null, the loop terminates.

When method getSitesFromHTMLParameters returns to init, lines 3256 construct the applet's GUI. Line 32 adds the JLabel "Choose a site to browse" to the NORTH of the JFrame's BorderLayout. Line 34 creates JList siteChooser to allow the user to select a Webpage to view. Lines 3554 register a ListSelectionListener to handle the siteChooser's events. Line 56 adds siteChooser to the CENTER of the JFrame's BorderLayout.

When the user selects one of the Web sites listed in siteChooser, the program calls method valueChanged (lines 3952). Line 42 obtains the selected site name from the JList. Line 45 passes the selected site name (the key) to HashMap method get, which locates and returns a reference to the corresponding URL object (the value) that is assigned to reference newDocument.

Line 48 uses Applet method getAppletContext to get a reference to an AppletContext object that represents the applet container. Line 51 uses the AppletContext reference browser to invoke method showDocument, which receives a URL object as an argument and passes it to the AppletContext (i.e., the browser). The browser displays in the current browser window the World Wide Web resource associated with that URL. In this example, all the resources are HTML documents.

For programmers familiar with HTML frames, there is a second version of AppletContext method showDocument that enables an applet to specify the so-called target frame in which to display the Web resource. This second version takes two argumentsa URL object specifying the resource to display and a string representing the target frame. There are some special target frames that can be used as the second argument. The target frame _blank results in a new Web browser window to display the content from the specified URL. The target frame _self specifies that the content from the specified URL should be displayed in the same frame as the applet (the applet's HTML page is replaced in this case). The target frame _top specifies that the browser should remove the current frames in the browser window, then display the content from the specified URL in the current window. [Note: If you are interested in learning more about HTML, the CD that accompanies this book contains three chapters from our book Internet and World Wide Web How to Program, Third Edition that introduce the current version of HTML (known as XHTML) and the Web page formatting capability known as Cascading Style Sheets (CSS).]

Error-Prevention Tip 24.1

The applet in Fig. 24.2 must be run from a Web browser, such as Mozilla or Microsoft Internet Explorer, to see the results of displaying another Web page. The appletviewer is capable only of executing appletsit ignores all other HTML tags. If the Web sites in the program contained Java applets, only those applets would appear in the appletviewer when the user selected a Web site. Each applet would execute in a separate appletviewer window.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look


Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams


Searching and Sorting

Data Structures



Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2



Accessing Databases with JDBC


JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

show all menu

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon © 2008-2017.
If you may any questions please contact us: