The J2EETM Tutorial
Home
TOC
Index
PREV TOP NEXT Search
Feedback

URL Connections

A Uniform Resource Locator (URL) specifies the location of a resource on the Web. The HTMLReaderBean class 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/htmlreader directory. To compile the code, go to the j2eetutorial/examples directory and type ant htmlreader. A sample HTMLReaderApp.ear file is in the j2eetutorial/examples/ears directory.

The getContents method of the HTMLReaderBean class returns a String that contains the contents of an HTML file. This method looks up the java.net.URL object associated with a coded name (url/MyURL), opens a connection to it, and then reads its contents from an InputStream. 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 the getContents method.

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

  1. In deploytool, open the j2eetutorial/examples/ears/HTMLReaderApp.ear file (FileOpen).
  2. Deploy the HTMLReaderApp application (ToolsDeploy). In the Introduction dialog box, make sure that you select the Return Client JAR checkbox.

Running the Client

  1. In a terminal window, go to the j2eetutorial/examples/ears directory.
  2. Set the APPCPATH environment variable to HTMLReaderAppClient.jar.
  3. Type the following command on a single line:
       runclient -client HTMLReaderApp.ear -name	
       HTMLReaderClient -textauth
     
    
  4. At the login prompts, enter guest for the user name and guest123 for the password.
  5. The client displays the contents of the index.html file that resides in the public_html directory of your J2EE SDK installation.
Home
TOC
Index
PREV TOP NEXT Search
Feedback