|
Home TOC Index |
|
Search
Feedback |
URL Connections
A Uniform Resource Locator (URL) specifies the location of a resource on the Web. The
HTMLReaderBeanclass shows how to connect to a URL from within an enterprise bean.The source code for this example is in the
j2eetutorial/examples/src/ejb/htmlreaderdirectory. To compile the code, go to thej2eetutorial/examplesdirectory and typeanthtmlreader. A sampleHTMLReaderApp.earfile is in the j2eetutorial/examples/earsdirectory.The
getContentsmethod of theHTMLReaderBeanclass returns aStringthat contains the contents of an HTML file. This method looks up thejava.net.URLobject associated with a coded name (url/MyURL), opens a connection to it, and then reads its contents from anInputStream. Before deploying the application, you must map the coded name (url/MyURL) to a JNDI name (a URL string). Here is the source code for thegetContentsmethod.public StringBuffer getContents() throws HTTPResponseException { Context context; URL url; StringBuffer buffer; String line; int responseCode; HttpURLConnection connection; InputStream input; DataInputStream dataInput; try { context = new InitialContext(); url = (URL)context.lookup("java:comp/env/url/MyURL"); connection = (HttpURLConnection)url.openConnection(); responseCode = connection.getResponseCode(); } catch (Exception ex) { throw new EJBException(ex.getMessage()); } if (responseCode != HttpURLConnection.HTTP_OK) { throw new HTTPResponseException("HTTP response code: " + String.valueOf(responseCode)); } try { buffer = new StringBuffer(); input = connection.getInputStream(); dataInput = new DataInputStream(input); while ((line = dataInput.readLine()) != null) { buffer.append(line); buffer.append('\n'); } } catch (Exception ex) { throw new EJBException(ex.getMessage()); } return buffer; }Running the HTMLReaderEJB Example
Deploying the Application
- In
deploytool, open thej2eetutorial/examples/ears/HTMLReaderApp.earfile (FileOpen).
- Deploy the
HTMLReaderAppapplication (ToolsDeploy). In the Introduction dialog box, make sure that you select the Return Client JAR checkbox.
Running the Client
- In a terminal window, go to the
j2eetutorial/examples/earsdirectory.- Set the
APPCPATHenvironment variable toHTMLReaderAppClient.jar.- Type the following command on a single line:
runclient -client HTMLReaderApp.ear -name HTMLReaderClient -textauth- At the login prompts, enter
guestfor the user name andguest123for the password.- The client displays the contents of the
index.htmlfile that resides in thepublic_htmldirectory of your J2EE SDK installation.
|
Home TOC Index |
|
Search
Feedback |