📄 ch28.htm
字号:
<HTML><HEAD><TITLE>developer.com - Reference</TITLE><META NAME="Author" CONTENT="developer.com"><META NAME="Keywords" CONTENT="javascript, ActiveX, VRML, Push, channel,push channel, applet, directory, news, community, developer, internet,intranet, java, java applet, J++, javabeans, java products, tools, javatools, JDK, java development kit, java development environment, JIT,JavaPlan, enterprise tools, JVM, Java Virtual Machine, Java resources, API,browser, java documentation, CDF, Common Desktop Format, RDF, ResourceDescription Framework, Netcaster, Netcast, Castanet, meta-language, metadata,solaris, Solaris, SUN, CGI, Perl, Oracle, database, network, Netscape API,Apache, apache, SSL, mSQL, Netscape, Fasttrack, FastTrack,industry standard, ActiveX bridge, web, internet, site, sitedesign, microsoft, active server pages, asp, iis, nt, win95, 95, html, cgi,frontpage, business, corporate, vbscript, javascript, activex, isapi,database, access, sql, server, www, 3.0, 3.01, 3.02, 3.03, 3.04, 4.0,4.0b2, 4.01, 4.03, 4.04, connection, online, commerce, publisher,publishing, publish, webmaster, dynamic html, dhtml, windows 98, netscape,netscape software, shareware, magazines, jobs, japan, free, freeware, freestuff"><META NAME="description" CONTENT="Developer.com is the leading onlineservice for developers. It includes Gamelan, the official directory for Java, as wellas news, information, tutorials, and directories for other Internet technologiesincluding ActiveX, JavaScript, perl, VRML, Java Beans, push technologies, andother Internet and intranet technologies. Developer.com is also the home ofDeveloper Direct, the Professional Developer's Store, where developers canpurchase and download thousands of Web, authoring and other developmentproducts at some of today's lowest prices."><META NAME="distribution" CONTENT="global"><META NAME="resource-type" CONTENT="document"><META NAME="language" CONTENT="en"></HEAD><BODY BACKGROUND="/images/curve_r-wide.gif" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#DD0000" VLINK="#999999" ALINK="#FF0000"><TABLE><TR><TD VALIGN=TOP WIDTH=120><A HREF="/" ><IMG SRC="/images/masthead_r.gif" WIDTH="100" HEIGHT="78" BORDER="0"ALT="Developer.com Logo"></a></TD><TD><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCBAN.REF/DT=null"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCBAN.REF/DT=null" HEIGHT="60" WIDTH="468" ALT="Click here to support our advertisers"><BR><CENTER>Click here to support our advertisers</CENTER></a></TD></TR></TABLE><!--outer table--><TABLE><!--outer table--><TR><!--outer table--><TD VALIGN="TOP"><!--navbar info --><table><tr><td><A HREF="http://www.developerdirect.com/" ><IMG SRC="/images/button_s.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>SHOPPING</b></font></a></td></tr><tr><td><A HREF="/community/jobs/c_jobs.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>JOB BANK</B></font></a></td></tr><tr><td><A HREF="http://www.classifieds2000.com/cgi-cls/display.exe?Developer+computer+searchcomputercategories"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>CLASSIFIEDS</B></font></a></td></tr><tr><td><A HREF="/directories/directories.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>DIRECTORIES</B></font></a></td></tr><tr><td><A HREF="/reference/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>REFERENCE</B></font></a><br><a href="/reference/r_library.html"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">Online Library</a></font></td></tr><tr><td><A HREF="/classroom/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>LEARNING CENTER</B></font></a></td></tr><tr><td><A HREF="/journal/"><IMG SRC="/images/button_n.gif" width="15" height="11" BORDER="0"><B><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">JOURNAL</font></B></a></td></tr><tr><td><A HREF="/news/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>NEWS CENTRAL</b></font></a></td></tr><tr><td><A HREF="/downloads/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>DOWNLOADS</b></font></a></td></tr><tr><td><A HREF="/community/" ><IMG SRC="/images/button_c.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>COMMUNITY</B></font></a></td></tr><tr><td><A HREF="/calendar/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>CALENDAR</b></font></a></td></tr><tr><td><A HREF="/about/"><IMG SRC="/images/button_a.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>ABOUT US</b></a></font></td></tr></table><table><tr><td><form action="/subscribe/list.cgi" method=post ><img src="/images/rule.gif" width="100" height="2"><br><B><FONT FACE="Arial, Helvetica" SIZE="-1">Journal:</b></font><br><input name='email' value='your e-mail' size="11"><input type='hidden' name='state' value='Subscribe'></td></tr><tr><td><input type='submit' value='Subscribe'><br><font size="-1">Get the weekly email highlights from the most popular journal for developers!<br><a href="http://www.developer.com/subscribe.html">Current issue</a><img src="/images/rule.gif" width="100" height="2"><input type='hidden' name='name' value='New Subscriber'></FORM></td></tr></table><!--/navbar--><font size="-1"><A HREF="http://www.developer.com">developer.com</a><BR><A HREF="http://www.developerdirect.com">developerdirect.com</a><BR><A HREF="http://www.htmlgoodies.com">htmlgoodies.com</a><BR><A HREF="http://www.javagoodies.com">javagoodies.com</a><br><A HREF="http://www.jars.com">jars.com</a><BR><a href="http://www.intranetjournal.com">intranetjournal.com</a><br><a href="http://www.javascripts.com">javascripts.com</a><br></font><!--outer table--></TD><!--outer table--><TD VALIGN="TOP"><BLOCKQUOTE><P><img src="/images/header_r.gif" width="440" height="50"><P><MAP NAME ="header_r2.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/author.html" COORDS ="361,0,440,29"><AREA SHAPE ="RECT" HREF ="/reference/basic.html" COORDS ="254,0,360,29"><AREA SHAPE ="RECT" HREF ="/reference/help.html" COORDS ="183,0,251,29"><AREA SHAPE ="RECT" HREF ="/reference/cool.html" COORDS ="100,0,181,29"><AREA SHAPE ="RECT" HREF ="/reference/mybook.html" COORDS ="0,0,100,29"></MAP><MAP NAME ="header_r1.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/personalize.html" COORDS ="339,0,439,29"></MAP><p><font face="Arial,Helvetica" size="-1" color="#006666"><A HREF="/reference/r_library.html"><B>All Categories</A> :</B><b><A HREF="/reference/r_java.html">Java</A></b></font><p><META><H1><FONT SIZE=6 COLOR=#Ff0000>Chapter 28</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Communications</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#URLObjects">URL Objects</A><UL><LI><A HREF="#ExampleCreatinganURLObject">Example: Creating an URL Object</A><LI><A HREF="#URLExceptions">URL Exceptions</A></UL><LI><A HREF="#TheAppletContext">The Applet Context</A><UL><LI><A HREF="#ExampleUsinganAppletContexttoLinktoanURL">Example: Using an AppletContext to Link to an URL</A><LI><A HREF="#ExampleUsinganAppletContextinanApplet">Example: Using an AppletContext in an Applet</A></UL><LI><A HREF="#CreatingaquotFavoriteURLsquotApplet">Creating a "Favorite URLs" Applet</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>Not to state the obvious, but because applets are used on theInternet, they have the ability to perform a few types of telecommunicationstasks. One of these tasks, connecting to other Web sites, is asnap to implement. Other tasks, such as accessing data in files,are difficult to implement because you constantly stumble overthe security restrictions built into applets. Dealing with theintricacies of Internet security is beyond the scope of this book.If you're interested in this topic, you should pick up an advancedJava book. In this chapter, though, you'll get a chance to useJava to communicate over the Internet by connecting to URLs thatthe user supplies.<H2><A NAME="URLObjects"><FONT SIZE=5 COLOR=#Ff0000>URL Objects</FONT></A></H2><P>In the previous chapter, you got a quick introduction to <TT>URL</TT>objects when you obtained the location of graphics and sound filesby calling the <TT>getDocumentBase()</TT> and <TT>getCodeBase()</TT>methods. You used the <TT>URL</TT> objects returned by these methodsin order to display images and play sounds that were stored onyour computer. In that case, the locations of the files were onyour own system. What you didn't know then is that you can createan <TT>URL</TT> object directly by calling its constructor. Usingthis technique, you can create <TT>URL</TT> objects that representother sites on the World Wide Web.<P>Although the <TT>URL</TT> class's constructor has several forms,the easiest to use requires a string argument holding the URLfrom which you want to create the object. Using this constructor,you create the <TT>URL</TT> object like this:<BLOCKQUOTE><PRE>URL url = new URL(str);</PRE></BLOCKQUOTE><P>This constructor's single argument is the complete URL of thelocation to which you want to connect. This URL string must beproperly constructed or the <TT>URL</TT> constructor will throwan exception (generate an error). You'll soon see what to do aboutsuch errors.<H3><A NAME="ExampleCreatinganURLObject">Example: Creating an URL Object</A></H3><P>Suppose you want to create an <TT>URL</TT> object for the URL<TT>http://www.sun.com</TT>, which is where you can find lotsof information about Java. You'd create the <TT>URL</TT> objectlike this:<BLOCKQUOTE><PRE>URL url = new URL("http://www.sun.com");</PRE></BLOCKQUOTE><P>If the <TT>URL</TT> construction goes okay, you can then use the<TT>URL</TT> object however you need to in your applet.<H3><A NAME="URLExceptions">URL Exceptions</A></H3><P>As I mentioned previously, if the argument for the <TT>URL</TT>constructor is in error (meaning that it doesn't use valid URLsyntax), the <TT>URL</TT> class throws an exception. Because the<TT>URL</TT> class is designed to throw an exception when necessary,Java gives you no choice except to handle that exception properly.This prevents the applet from accidentally attempting to use adefective <TT>URL</TT> object. You'll learn all the details abouthandling exceptions in <A HREF="ch30.htm" >Chapter 30</A>, "Exceptions." Fornow, though, you need to know how to handle the <TT>URL</TT> exceptionbecause your applets will not compile properly until you add theexception-handling code.<P>Basically, when you need to watch out for an exception, you enclosethe code that may generate the error in a <TT>try</TT> programblock. If the code in the block generates an exception, you handlethat exception in a <TT>catch</TT> program block. (It's no coincidencethat when code "throws" an exception, Java expects theprogram to "catch" that exception.) When you createan <TT>URL</TT> object from a string, you must watch out for the<TT>MalformedURLException</TT> exception, which is one of themany exceptions defined by Java. To do this, use the <TT>try</TT>and <TT>catch</TT> program blocks, as shown in Listing 28.1.<HR><BLOCKQUOTE><B>Listing 28.1 LST28_1.TXT: Handling URL Exceptions.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>try{ URL url = new URL(str);}catch (MalformedURLException e){ DisplayErrorMessage();}</PRE></BLOCKQUOTE><HR><H2><A NAME="TheAppletContext"><FONT SIZE=5 COLOR=#Ff0000>The Applet Context</FONT></A></H2><P>Once you have the <TT>URL</TT> object created, you need a wayto pass it on to the browser in which the applet is running. Itis the browser, after all, that will make the Web connection foryou. But, how do you refer to the browser from within your applet?You call the <TT>getAppletContext()</TT> method, which returnsan <TT>AppletContext</TT> object. This <TT>AppletContext</TT>object represents the browser in which the applet is running.You call <TT>getAppletContext()</TT> like this:<BLOCKQUOTE><PRE>AppletContext context = getAppletContext();</PRE></BLOCKQUOTE><P>Once you have the context, you can link to the URL representedby the <TT>URL</TT> object you already created. You do this bycalling the <TT>AppletContext</TT> object's <TT>showDocument()</TT>method, like this:<BLOCKQUOTE><PRE>context.showDocument(url);</PRE></BLOCKQUOTE><P>If all goes well, the above line will connect you to the requestedURL.<H3><A NAME="ExampleUsinganAppletContexttoLinktoanURL">Example: Using an AppletContext to Link to an URL</A></H3><P>Suppose that you want to enable the user to enter an URL stringin your applet and then use <TT>URL</TT> and <TT>AppletContext</TT>objects to link to that URL. Listing 28.2 shows how you mightaccomplish this feat of Internet prestidigitation:<HR><BLOCKQUOTE><B>Listing 28.2 LST28_2.TXT: Linking to an URL.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>String str = GetURLStringFromUser();try{ URL url = new URL(str); AppletContext context = getAppletContext(); context.showDocument(url);}catch (MalformedURLException e){ DisplayErrorMessage();}</PRE></BLOCKQUOTE><HR><P>In Listing 28.2, the program first calls a method that retrievesa text string from the user. This text string is the URL to whichthe user wants to connect. Then, the <TT>try</TT> program blockstarts. The first line inside the <TT>try</TT> block attemptsto create an <TT>URL</TT> object from the string the user entered.Of course, because user's often make mistakes when typing in longstrings of characters, the string the user entered may not bea syntactically valid URL. In that case, program execution automaticallyjumps to the <TT>catch</TT> program block, where your applet displaysan appropriate error message. If the <TT>URL</TT> object getscreated okay, though, the program finishes the code in the <TT>try</TT>block, getting the <TT>AppletContext</TT> object and making thelink to the URL. In this case, Java completely ignores the <TT>catch</TT>block.<H3><A NAME="ExampleUsinganAppletContextinanApplet">Example: Using an AppletContext in an Applet</A></H3><P>Ready for a full-fledged example? Listing 28.3 is a complete appletthat enables the user to link to an URL. Listing 28.4 is the HTMLdocument that loads the applet. Because this applet actually interactswith a browser and the Internet, you must have made your Internetconnection before running the applet. Then, to run the applet,load its HTML document into a Java-compatible browser such asNetscape Navigator 2.0. When you do, you'll see a window similarto that shown in Figure 28.1. In this figure, the user has alreadyentered the URL he wishes to visit. In Figure 28.2, the browserhas made the requested connection. Figure 28.3 shows the browserwhen the user enters an invalid URL string.<P><A HREF="f28-1.gif"><B> Figure 28.1 : </B><I>Here, the user is ready to make a connection.</I></A><P><P><A HREF="f28-2.gif"><B> Figure 28.2 : </B><I>If the URL is OK, the browser connects.</I></A><P><P><A HREF="f28-3.gif"><B> Figure 28.3 : </B><I>If the URL is constructed improperly, the applet displays an error message.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -