Writing Web Applications With WAI: Netscape Enterprise Server/FastTrack Server, Version 3.0/3.01

[Contents] [Previous] [Next] [Index]

Chapter 6
Writing a WAI Application in Java

WAI provides a set of Java classes and methods that you can use to write a WAI application. Your Java application should:

After you write and compile your application, see the section "Running Your Web Service" for instructions on setting up and running your web service.

Before continuing on, note the following points:

The rest of this chapter explains how to write a WAI application in Java.

Declaring a Class for Your Web Service

The first step in developing a WAI application in Java is to declare a class that derives from the Netscape WAIWebApplicationService base class. (This class represents a web application service.)

For example, the WASP example provided with the web server declares a MyWebApplicationService class, which is derived from the WAIWebApplicationService base class:

import java.applet.*; 
import java.io.*; 
import java.awt.*; 
import java.net.*; 
import java.util.*; 
import java.lang.*; 
/* Make sure to import these classes. */
import org.omg.CORBA.*; 
import org.omg.CosNaming.*;
import netscape.WAI.*; 
...
/* 
* Implementation class for A WAS. 
* Extends wrapper class for WAI CORBA object 
*/ 
class MyWebApplicationService extends WAIWebApplicationService { 
   String instanceName;
   MyWebApplicationService(java.lang.String name) throws 
   org.omg.CosNaming.NamingContextPackage.CannotProceed, 
   org.omg.CosNaming.NamingContextPackage.InvalidName, 
   org.omg.CosNaming.NamingContextPackage.AlreadyBound, 
   org.omg.CORBA.SystemException{ 
      super(name); 
      instanceName = name; 
   }
...
The class that you define represents your web service. You need to define the following methods for your class; these methods are virtual methods in the WAIWebApplicationService base class:

Defining a Method to Process Requests

The method that processes incoming HTTP requests (not all requests, just the requests directed specifically at your service) should use the following syntax:

public int Run(netscape.WAI.HttpServerRequest request);
request represents the HTTP request to be processed. You can call the methods of this object to get data from the request, set data in the response headers, and send the response back to the client.

The rest of this section explains how you can use these methods and objects to process the request. WAI functions enable you to do the following tasks:

Getting Data from the Request

Using an object of the netscape.WAI.HttpServerRequest class (see the section "netscape::WAI::HttpServerRequest" for details), you can get data from the client's HTTP request. You can call functions accomplish the following tasks:

Getting Headers from the HTTP Request

Given an object of the netscape.WAI.HttpServerRequest class, you can get headers from the corresponding HTTP request by calling the getRequestHeader method. For example, the following section of code gets the user-agent HTTP request header from the incoming request:

public int Run(netscape.WAI.HttpServerRequest request) { 
   ...
   /* Prepare an output stream to send data back to the client. */
   ByteArrayOutputStream streamBuf = new ByteArrayOutputStream(); 
   PrintStream content = new PrintStream(streamBuf);
   ...
   /* Get the value of the user-agent header. */
   org.omg.CORBA.StringHolder value = new org.omg.CORBA.StringHolder(); 
   if (request.getRequestHeader("user-agent", value) == HttpServerReturnType.Success){ 
      content.print("User agent: " + value.value); 
   }
   ...
}
In addition to HTTP headers, you can get other types of information (such as CGI 1.1 environment variables) from the HTTP request by calling the getRequestInfo method of the netscape.WAI.HttpServerRequest class.

The section "getRequestInfo" lists the types of information you can retrieve from the request. Note that the CGI 1.1 environment variables that describe the server are accessible through the getInfo method. See "Getting Information about the Server" for details.

The following section of code gets and prints the value of the REMOTE_ADDR CGI 1.1 environment variable from the incoming request:

public int Run(netscape.WAI.HttpServerRequest request) { 
   ...
   /* Prepare an output stream to send data back to the client. */
   ByteArrayOutputStream streamBuf = new ByteArrayOutputStream(); 
   PrintStream content = new PrintStream(streamBuf);
   ...
   /* Get the client's IP address. */
   org.omg.CORBA.StringHolder value = new org.omg.CORBA.StringHolder(); 
   if (request.getRequestInfo("REMOTE_ADDR", value) == HttpServerReturnType.Success){ 
      content.print("Client addr: " + value.value); 
   }
   ...
}

Getting Information about the Server

WAI also provides methods for getting information about the server, such as the server identifier or CGI 1.1 environment variables that describe the server (for example, SERVER_NAME or SERVER_PORT).

These methods are available as part of the netscape.WAI.HttpServerContext class (for more information, see the section "netscape::WAI::HttpServerContext"). You can get an object of this class by using the getContext method of the netscape.WAI.HttpServerRequest class.

For example, the following section of code gets an netscape.WAI.HttpServerContext object:

public int Run(netscape.WAI.HttpServerRequest request) { 
   ...
   /* Get the HttpServerContext object describing this web server. */
   HttpServerContext context = request.getContext(); 
   ...
}
To get information about the server, you can call the getInfo method of the netscape.WAI.HttpServerContext object and specify the type of information that you want to retrieve. For example, the following section of code gets the value of the SERVER_PORT CGI 1.1 environment variable:

public int Run(netscape.WAI.HttpServerRequest request) { 
   ...
   /* Prepare an output stream to send data back to the client. */
   ByteArrayOutputStream streamBuf = new ByteArrayOutputStream(); 
   PrintStream content = new PrintStream(streamBuf);
   /* Get the HttpServerContext object for this web server. */
   HttpServerContext context = request.getContext(); 
   ...
   /* Get the port number that the web server listens to. */
   org.omg.CORBA.StringHolder svar; 
   if (context.getInfo("SERVER_PORT", svar) == HttpReturnType.Success){ 
      content.print("Web Server port number: " + svar); 
   } 
   ...
}
For a list of the types of information you can retrieve from this method, see the section "getInfo".

You can also use methods that specifically retrieve a certain type of information. For example, to get the port number that the server listens to, you can call the getPort method:

public int Run(netscape.WAI.HttpServerRequest request) { 
   ...
   /* Prepare an output stream to send data back to the client. */
   ByteArrayOutputStream streamBuf = new ByteArrayOutputStream(); 
   PrintStream content = new PrintStream(streamBuf);
   /* Get the HttpServerContext object for this web server. */
   HttpServerContext context = request.getContext(); 
   ...
   /* Get the port number that the web server listens to. */
   int portNum = 0; 
   if ((portNum = context.getPort()) != 0){ 
      content.print("Web Server port number: " + portNum); 
   } 
   ...
}
For details on getting server information, see the section "netscape::WAI::HttpServerContext".

Getting and Setting Cookies in the Client

Before a client accesses a URL, the client checks the domain name in the URL against the cookies that it has. If any cookies are from the same domain as the URL, the client includes a header in the HTTP request that contains the name/value pairs from the matching cookies.

The Cookie header has the following format:

Cookie: name=value; [name1=value1; name2=value2 ... ]
To get these name/value pairs from the HTTP request, call the getCookie method. To set your own name/value pairs in a client, call the setCookie method.

The following example illustrates how you can use these methods to get and set cookies in the client.

public int Run(netscape.WAI.HttpServerRequest request) 
{ 
   ...
   org.omg.CORBA.StringHolder 
   cookiebuff = new org.omg.CORBA.StringHolder();
   /* If no cookie has been set in the client, set a cookie. */
   if (request.getCookie(cookiebuff)== HttpServerReturnType.Failure) 
      request.setCookie("MY_NAME", "My Value", "", "", "/", false); 
   ...
}

Sending the Response Back to the Client

Methods of the HttpServerRequest class also allow you to control the response sent back to the client. You can call these functions to accomplish the following tasks:

Setting Headers in the Response

WAI includes functions that you can use to set headers in the response that you want sent back to the client. You can call the addResponseHeader method to set any header in the response. For example, the following section of code adds the Pragma header to the response:

public int Run(netscape.WAI.HttpServerRequest request) 
{ 
   ...
   request.addResponseHeader("Pragma", "no-cache");
   ...
}
You can also call functions that set specific types of headers. For example, you can call:

Setting the Status of the Response

To set the status of the response sent back to the client, call the setResponseStatus method. For example, the following section of code sets the response code to a 404 status code ("File Not Found"):

public int Run(netscape.WAI.HttpServerRequest request) 
{ 
   ...
   request.setResponseStatus(404, "");
   ...
}

Sending the Response

After you have specified the length of the content you want sent back to the client, you can start sending the response to the client. Call the StartResponse method to start sending the response.

To send the rest of the data to the client, call the WriteClient method.

The following example sends the string Hello World back to the client:

public int Run(netscape.WAI.HttpServerRequest request) 
{ 
   ...
   /* Prepare an output stream to send data back to the client. */
   ByteArrayOutputStream streamBuf = new ByteArrayOutputStream(); 
   PrintStream content = new PrintStream(streamBuf);
   ...
   /* Send "Hello World" to the print stream. */
   String buffer = "Hello World\n"; 
   content.print(buffer); 
   /* Convert the string to a byte array for WriteClient(). */
   HttpServerReturnType rc; 
   byte[] outbuff = streamBuf.toByteArray(); 
   try { 
      /* Specify the length of the data you will send. */
      rc = request.setResponseContentLength(outbuff.length); 
      /* Start sending your response. */
      request.StartResponse(); 
   } 
   catch(org.omg.CORBA.SystemException e){ 
   } 
   /* Write data back to the client. */
   int write_cnt = request.WriteClient(outbuff); 
   ...
}

Redirecting Users to Another Page

In your WAI application, you can also redirect users to a different page than the requested page. You can either automatically redirect the user to a new page, or you can present the user with a link to click on manually.

To automatically redirect the user to a different page, do the following:

  1. Call the addResponseHeader method to add a Location header, which points to the new location.

  2. Call the setResponseStatus method to set the response status to 301 (if the page has permanently moved) or 302 (if the page has temporarily moved).

  3. Call the StartResponse method to send the response back to the client.
For example:

public int Run(HttpServerRequest request){ 
try { 
   request.addResponseHeader("Location", "http://www.newsite.com/"); 
   request.setResponseStatus(301, "Moved permanently to newsite.com!"); 
   request.StartResponse(); 
} 
catch(org.omg.CORBA.SystemException e){ 
} 
catch(java.lang.Exception e) { 
   System.err.println(e); 
}
return 0;
}
To give the user the choice of going to the new location (rather than automatically redirecting the URL), you can call the RespondRedirect method:

public int Run(HttpServerRequest request){ 
request.RespondRedirect("http://www.newsite.com/"); 
try { 
   request.StartResponse(); 
} 
catch(org.omg.CORBA.SystemException e){ 
} 
catch(java.lang.Exception e) { 
   System.err.println(e); 
} 
return 0; 
} 
Calling this method will send the following page back to the client:

Moved Temporarily
This document has moved to a new location. Please update your documents and hotlists accordingly.
The word "location" on this page is a link pointing to the new location of the page.

Providing Information About the Service

Part of the WAIWebApplicationService base class is the virtual getServiceInfo method. When you write your web application class (which is derived from the base class), you need to include a definition of this method.

The getServiceInfo method should provide information about the web service, such as the name of the author, the version of the service, and so on.

The following sections of code defines the getServiceInfo method for a web service class WebApplicationServicePrototype.

...
public java.lang.String getServiceInfo(){ 
   return "Java Test Web Application Service V1.0\nCopyright Netscape Communications Corporation\nAuthor: Mozilla\n"; 
}
...

Registering Your Web Application Service

  1. Initialize the object request broker (ORB) and the basic object adaptor (BOA):

  2. Create an instance of your class and assign an instance name to the object.
    You need to register your web service to the web server under this instance name. The instance name that you select for your web service can be an arbitrary name; it does not need to be the same name as your application. (For example, if your application is named MyApp.class, your instance name can be MyWebService. They do not need to have the same name.)
    Note, however, that your instance name must be unique. No other registered WAI application can have the same name.

Registering With a Web Server

To register your application with the web server's built-in name service:

  1. Call the RegisterService method.
    Pass the name of the web server's hostname and port number as an argument (in the form hostname:portnumber) to this method.
    Note that if your web server is running with SSL enabled, you need to specify a different value for this argument. For details, see "Registering With an SSL Enabled Server".

  2. After you register the service, call the impl_is_ready() method of the BOA object to indicate that your service prepared to receive incoming requests.

Registering With a Web Server

The following section of code creates the web service mpi from the web service class MyWebApplicationService. The example registers this object to the web server under the instance name MyJavaService.

...
String host = "myhost.mydomain.com:81";
String instanceName = "MyJavaService";
try { 
   /* Initialize the object request broker (ORB). */
   ORB orb = org.omg.CORBA.ORB.init(); 
   /* Initialize the basic object adapter (BOA). */
   BOA boa = orb.BOA_init(); 
   /* Create the web service. */
   try { 
      MyWebApplicationService 
      mpi = new MyWebApplicationService(instanceName);
      System.out.println(mpi + " is ready."); 
      /* Register the web service. */
      mpi.RegisterService(host); 
      /* Wait for incoming requests */
      boa.impl_is_ready(); 
   } 
catch(java.lang.Exception e){ 
      System.out.println("WAS failed to initialize."); 
      System.err.println(e); 
} 
...

Registering With an SSL Enabled Server

If your web server has SSL enabled, you need to use the following format specifying the argument to RegisterService. (In the case of an SSL-enabled server, the method gets the object reference from the Interoperable Object Reference (IOR) file.)

file:path_to_IOR_file
This file is located in the wai/NameService directory under your server root directory. The file uses the following naming convention:

server_id.IOR 
For example, on the machine named preston, the IOR might be named https-preston.IOR.

Suppose your web server is running on the host machine named feathers on port number 8080. Suppose that the server is installed under the server root directory /usr/netscape/suitespot with the server identifier https-feathers. If SSL is enabled, you register your WAI application in Java by calling:

RegisterService("file:/usr/netscape/suitespot/wai/NameService/https-feathers.IOR" ); 
The RegisterService method uses the Interoperable Object Reference (IOR) file to get the object reference for the naming service. This object reference is used to register your application.

Running Your Web Service

After you write and compile your application, you can run your application to make your web service available. The web server should recognize your application, if you've registered it (see "Registering Your Web Application Service").

End users can access your service by going to the URL:

http://server_name:port_number/iiop/instance_name
For example, you can access the JavaWASP example by going to the URL:

http://server_name:port_number/iiop/JavaWASP


[Contents] [Previous] [Next] [Index]

Last Updated: 12/04/97 16:12:39


Copyright © 1997 Netscape Communications Corporation

Any sample code included above is provided for your use on an "AS IS" basis, under the Netscape License Agreement - Terms of Use