Table of Contents | Previous | Next | Index


Chapter 21
LiveConnect Overview

This chapter describes using LiveConnect technology to let Java and JavaScript code communicate with each other. The chapter assumes you are familiar with Java programming.

This chapter contains the following sections:

For additional information on using LiveConnect, see the JavaScript technical notes on the DevEdge site.


What Is LiveConnect?

LiveConnect lets you connect server-side JavaScript applications to Java components or classes on the server. Through Java, you can connect to CORBA-compliant distributed objects using Netscape Internet Service Broker for Java.

Your JavaScript application may want to communicate with code written in other languages, such as Java or C. To communicate with Java code, you use JavaScript's LiveConnect functionality. To communicate with code written in other languages, you have several choices:

This chapter discusses using LiveConnect to access non-JavaScript code from JavaScript applications.

Ultimately, LiveConnect allows the JavaScript objects in your application to interact with Java objects. These Java objects are instances of classes on the server's CLASSPATH. See "Setting Up for LiveConnect" on page 48 for information on setting CLASSPATH appropriately. LiveConnect works for both client-side and server-side JavaScript but has different capabilities appropriate to each environment.

If you have a CORBA service and you have the IDL for it, you can generate Java stubs. The Java stubs can then be accessed from JavaScript using LiveConnect, thus giving you access to your service from JavaScript. For the most part, connecting to CORBA services in this way is just like accessing any other Java code. For this reason, this chapter first talks about using LiveConnect to communicate between Java and JavaScript. Later, it describes what you need to do to access CORBA services.

This chapter assumes you are familiar with Java programming. For information on using Java with Netscape servers, see Enterprise Server 3.0: Notes for Java Programmers. For other information on LiveConnect, see the DevEdge Library.

For all available Java classes, you can access static public properties or methods of the class, or create instances of the class and access public properties and methods of those instances. Unlike on the client, however, you can access only those Java objects that were created by your application or created by another JavaScript application and then stored as a property of the server object.

If a Java object was created by a server application other than a server-side JavaScript application, you cannot access that Java object. For example, you cannot access a Java object created by a WAI plug-in, NSAPI extension, or an HTTP applet.

When you call a method of a Java object, you can pass JavaScript objects to that method. Java code can set properties and call methods of those JavaScript objects. In this way, you can have both JavaScript code that calls Java code and Java code that calls JavaScript code.

Java code can access a JavaScript application only in this fashion. That is, a Java object cannot invoke a JavaScript application unless that JavaScript application (or another JavaScript application) has itself accessed an appropriate Java object and invoked one of its methods.


Working with Wrappers

In JavaScript, a wrapper is an object of the target language data type that encloses an object of the source language. On the JavaScript side, you can use a wrapper object to access methods and fields of the Java object; calling a method or accessing a property on the wrapper results in a call on the Java object. On the Java side, JavaScript objects are wrapped in an instance of the class netscape.javascript.JSObject and passed to Java.

When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type JSObject; when a JSObject is sent from Java to JavaScript, the runtime engine unwraps it to its original JavaScript object type. The JSObject class provides an interface for invoking JavaScript methods and examining JavaScript properties.


JavaScript to Java Communication

When you refer to a Java package or class, or work with a Java object or array, you use one of the special LiveConnect objects. All JavaScript access to Java takes place with these objects, which are summarized in the following table.

Table 21.1 The LiveConnect Objects
Object Description

JavaArray

A wrapped Java array, accessed from within JavaScript code.

JavaClass

A JavaScript reference to a Java class.

JavaObject

A wrapped Java object, accessed from within JavaScript code.

JavaPackage

A JavaScript reference to a Java package.

NOTE: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See "Data Type Conversions" on page 413 for complete information.
In some ways, the existence of the LiveConnect objects is transparent, because you interact with Java in a fairly intuitive way. For example, you can create a Java String object and assign it to the JavaScript variable myString by using the new operator with the Java constructor, as follows:

var myString = new java.lang.String("Hello world")
In the previous example, the variable myString is a JavaObject because it holds an instance of the Java object String. As a JavaObject, myString has access to the public instance methods of java.lang.String and its superclass, java.lang.Object. These Java methods are available in JavaScript as methods of the JavaObject, and you can call them as follows:

myString.length() // returns 11
You access constructors, fields, and methods in a class with the same syntax that you use in Java. For example, the following JavaScript code uses properties of the request object to create a new instance of the Bug class and then assigns that new instance to the JavaScript variable bug. Because the Java class requires an integer for its first field, this code first converts the request string property to an integer before passing it to the constructor.

var bug = new Packages.bugbase.Bug(
   parseInt(request.bugId),
   request.bugPriority,
   request);

The Packages Object

If a Java class is not part of the java, sun, or netscape packages, you access it with the Packages object. For example, suppose the Redwood corporation uses a Java package called redwood to contain various Java classes that it implements. To create an instance of the HelloWorld class in redwood, you access the constructor of the class as follows:

var red = new Packages.redwood.HelloWorld()
You can also access classes in the default package (that is, classes that don't explicitly name a package). For example, if the HelloWorld class is directly in the CLASSPATH and not in a package, you can access it as follows:

var red = new Packages.HelloWorld()
The LiveConnect java, sun, and netscape objects provide shortcuts for commonly used Java packages. For example, you can use the following:

var myString = new java.lang.String("Hello world")
instead of the longer version:

var myString = new Packages.java.lang.String("Hello world")
By default, $NSHOME\js\samples directory, where $NSHOME is the directory in which the server was installed, is on the server's CLASSPATH. You can put your packages in this directory. Alternatively, you can choose to put your Java packages and classes in any other directory. If you do so, make sure the directory is on your CLASSPATH.

Working with Java Arrays

When any Java method creates an array and you reference that array in JavaScript, you are working with a JavaArray. For example, the following code creates the JavaArray x with ten elements of type int:

theInt = java.lang.Class.forName("java.lang.Integer")
x = java.lang.reflect.Array.newInstance(theInt, 10)
Like the JavaScript Array object, JavaArray has a length property which returns the number of elements in the array. Unlike Array.length, JavaArray.length is a read-only property, because the number of elements in a Java array are fixed at the time of creation.

Package and Class References

Simple references to Java packages and classes from JavaScript create the JavaPackage and JavaClass objects. In the earlier example about the Redwood corporation, for example, the reference Packages.redwood is a JavaPackage object. Similarly, a reference such as java.lang.String is a JavaClass object.

Most of the time, you don't have to worry about the JavaPackage and JavaClass objects--you just work with Java packages and classes, and LiveConnect creates these objects transparently.

JavaClass objects are not automatically converted to instances of java.lang.Class when you pass them as parameters to Java methods--you must create a wrapper around an instance of java.lang.Class. In the following example, the forName method creates a wrapper object theClass, which is then passed to the newInstance method to create an array.

theClass = java.lang.Class.forName("java.lang.String")
theArray = java.lang.reflect.Array.newInstance(theClass, 5)

Arguments of Type char

You cannot pass a one-character string to a Java method which requires an argument of type char. You must pass such methods an integer which corresponds to the Unicode value of the character. For example, the following code assigns the value "H" to the variable c:

c = new java.lang.Character(72)

Example of JavaScript Calling Java

The $NSHOME\js\samples\bugbase directory includes a simple application illustrating the use of LiveConnect. This section describes the JavaScript code in that sample application. See "Example of Calling Server-Side JavaScript" on page 412 for a description of this application's Java code.

The bugbase application represents a simple bug database. You enter a bug by filling in a client-side form with the bug number, priority, affected product, and a short description. Another form allows you to view an existing bug.

The following JavaScript processes the enter action:

// Step 1. Verify that ID was entered.
if (request.bugId != "") {
   // Step 2. Create Bug instance and assign to variable.
   var bug = new Packages.bugbase.Bug(parseInt(request.bugId),
      request.bugPriority, request);
   // Step 3. Get access to shared array and store instance there.
   project.bugsLock.lock();
   project.bugs[parseInt(request.bugId)] = bug;
   project.bugsLock.unlock();
   // Step 4. Display information.
   write("<P><b><I>====>Committed bug: </I></b>");
   write(bug, "<BR>");
}
// Step 5. If no ID was entered, alert user.
else {
   write("<P><b><I>====>Couldn't commit bug: please complete
      all fields.</I></b>");
}
The steps in this code are:

  1. Verify that the user entered an ID for the bug. Enter the bug only in this case.
  2. Create an instance of the Java class Bug, and assign that instance to the bug variable. The Bug class constructor takes three parameters: two of them are properties of the request object; the third is the JavaScript request object itself. Because they are form elements, these request properties are both JavaScript strings. The code changes the ID to an integer before passing it to the Java constructor. Having passed the request object to the Java constructor, that constructor can then call its methods. This process is discussed in "Example of Calling Server-Side JavaScript" on page 412.
  3. Use project.bugsLock to get exclusive access to the shared project.bugs array and then store the new Bug instance in that array, indexed by the bug number specified in the form. Notice that this code stores a Java object reference as the value of a property of a JavaScript object. For information on locking, see "Sharing Objects Safely with Locking" on page 268.
  4. Display information to the client about the bug you have just stored.
  5. If no bug ID was entered, display a message indicating that the bug couldn't be entered in the database.

Java to JavaScript Communication

If you want to use JavaScript objects in Java, you must import the netscape.javascript package into your Java file. This package defines the following classes:

These classes are delivered in either a .jar or a .zip file. See the Server-Side JavaScript Reference for more information about these classes.

To access the LiveConnect classes, place the .jar or .zip file in the CLASSPATH of the JDK compiler in either of the following ways:

For example, in Navigator 4. 0 for Windows NT, the classes are delivered in the java40.jar file in the Program\Java\Classes directory beneath the Navigator directory. You can specify an environment variable in Windows NT by double-clicking the System icon in the Control Panel and creating a user environment variable called CLASSPATH with a value similar to the following:

D:\Navigator\Program\Java\Classes\java40.jar
See the Sun JDK documentation for more information about CLASSPATH.

NOTE: Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. See "Data Type Conversions" on page 413 for complete information.

Using the LiveConnect Classes

All JavaScript objects appear within Java code as instances of netscape.javascript.JSObject. When you call a method in your Java code, you can pass it a JavaScript object as one of its argument. To do so, you must define the corresponding formal parameter of the method to be of type JSObject.

Also, any time you use JavaScript objects in your Java code, you should put the call to the JavaScript object inside a try...catch statement which handles exceptions of type netscape.javascript.JSException. This allows your Java code to handle errors in JavaScript code execution which appear in Java as exceptions of type JSException.

Accessing JavaScript with JSObject

For example, suppose you are working with the Java class called JavaDog. As shown in the following code, the JavaDog constructor takes the JavaScript object jsDog, which is defined as type JSObject, as an argument:

import netscape.javascript.*;

public class JavaDog
{
    public String dogBreed;
    public String dogColor;
    public String dogSex;

    // define the class constructor
    public JavaDog(JSObject jsDog)
    {
        // use try...catch to handle JSExceptions here
        this.dogBreed = (String)jsDog.getMember("breed");
        this.dogColor = (String)jsDog.getMember("color");
        this.dogSex = (String)jsDog.getMember("sex");
    }
}
Notice that the getMember method of JSObject is used to access the properties of the JavaScript object. The previous example uses getMember to assign the value of the JavaScript property jsDog.breed to the Java data member JavaDog.dogBreed.

NOTE: A more realistic example would place the call to getMember inside a try...catch statement to handle errors of type JSException. See "Handling JavaScript Exceptions in Java" on page 410 for more information.
To get a better sense of how getMember works, look at the definition of the custom JavaScript object Dog:

function Dog(breed,color,sex) {
   this.breed = breed
   this.color = color
   this.sex = sex
}
You can create a JavaScript instance of Dog called gabby as follows:

gabby = new Dog("lab","chocolate","female")
If you evaluate gabby.color, you can see that it has the value "chocolate". Now suppose you create an instance of JavaDog in your JavaScript code by passing the gabby object to the constructor as follows:

javaDog = new Packages.JavaDog(gabby)
If you evaluate javaDog.dogColor, you can see that it also has the value "chocolate", because the getMember method in the Java constructor assigns dogColor the value of gabby.color.

Handling JavaScript Exceptions in Java

When JavaScript code called from Java fails at run time, it throws an exception. If you are calling the JavaScript code from Java, you can catch this exception in a try...catch statement. The JavaScript exception is available to your Java code as an instance of netscape.javascript.JSException. JSException is a Java wrapper around any exception type thrown by JavaScript, similar to the way that instances of JSObject are wrappers for JavaScript objects.

Use JSException when you are evaluating JavaScript code in Java. If the JavaScript code is not evaluated, either due to a JavaScript compilation error or to some other error that occurs at run time, the JavaScript interpreter generates an error message that is converted into an instance of JSException.

For example, you can use a try...catch statement such as the following to handle LiveConnect exceptions:

try {
   global.eval("foo.bar = 999;");
} catch (Exception e) {
   if (e instanceof JSException) {
      jsCodeFailed()";
   } else {
      otherCodeFailed();
   }
}
In this example, the eval statement fails if foo is not defined. The catch block executes the jsCodeFailed method if the eval statement in the try block throws a JSException; the otherCodeFailed method executes if the try block throws any other error.

Accessing Server-Side JavaScript

Now let's look specifically at using Java to access server-side JavaScript. For a Java method to access server-side JavaScript objects, it must have been called from a server-side JavaScript application. In client-side JavaScript, Java can initiate an interaction with JavaScript. On the server, Java cannot initiate this interaction.

NOTE: When you recompile a Java class that is used in a JavaScript application, the new definition may not take effect immediately. If any JavaScript application running on the web server has a live reference to an object created from the old class definition, all applications continue to use the old definition. For this reason, when you recompile a Java class, you should restart any JavaScript applications that access that class.

Threading

Java allows you to create separate threads of execution. You need to be careful using this feature when your Java code interacts with JavaScript code.

Every server-side JavaScript request is processed in a thread known as the request thread. This request thread is associated with state information such as the JavaScript context being used to process the request, the HTTP request information, and the HTTP response buffer.

When you call Java code from a JavaScript application, that Java code runs in the same request thread as the original JavaScript application. The Java code in that thread can interact with the JavaScript application and be guaranteed that the environment is as it expects. In particular, it can rely on the associated state information.

However, you can create a new thread from your Java code. If you do, that new thread cannot interact with the JavaScript application and cannot rely on the state information associated with the original request thread. If it attempts to do so, the behavior is undefined. For example, a Java thread you create cannot initiate any execution of JavaScript code using JSObject, nor can it use writeHttpOutput, because this method requires access to the HTTP response buffer.

Example of Calling Server-Side JavaScript

The $NSHOME\js\samples\bugbase directory includes a simple application that illustrates the use of LiveConnect. This section describes the sample application's Java code. See "Example of JavaScript Calling Java" on page 406 for a description of the basic workings of this application and of its JavaScript code.

// Step 1. Import the needed Java objects.
package Bugbase;
import netscape.javascript.*;
import netscape.server.serverenv.*;
// Step 2. Create the Bug class.
public class Bug {
   int id;
   String priority;
   String product;
   String description;
   String submitter;
   // Step 3. Define the class constructor.
   public Bug(int id, String priority, JSObject req)
   throws java.io.IOException
   {
      // write part of http response
      NetscapeServerEnv.writeHttpOutput("Java constructor: Creating
         a new bug.<br>");
      this.id = id;
      this.priority = priority;
      this.product = (String)req.getMember("bugProduct");
      this.description = (String)req.getMember("bugDesc");
   }
   // Step 4. Return a string representation of the object.
   public String toString()
   {
      StringBuffer result = new StringBuffer();
      result.append("\r\nId = " + this.id
         + "; \r\nPriority = " + this.priority
         + "; \r\nProduct = " + this.product
         + "; \r\nDescription = " + this.description);
      return result.toString();
   }   }
Many of the steps in this code are not specific to communicating with JavaScript. It is only in steps 1 and 3 that JavaScript is relevant.

  1. Specify the package being used in this file and import the netscape.javascript and netscape.server.serverenv packages. If you omit this step, you cannot use JavaScript objects.
  2. Create the Java Bug class, specifying its fields.
  3. Define the constructor for this class. This constructor takes three parameters: an integer, a string, and an object of type JSObject. This final parameter is the representation of a JavaScript object in Java. Through the methods of this object, the constructor can access properties and call methods of the JavaScript object. In this case, it uses the getMember method of JSObject to get property values from the JavaScript object. Also, this method uses the writeHttpOutput method of the predefined NetscapeServerEnv object (from the netscape.server.serverenv package) to print information during object construction. This method writes a byte array to the same output stream used by the JavaScript write function.
  4. Define the toString method. This is a standard method for a Java object that returns a string representation of the fields of the object.

Data Type Conversions

Because Java is a strongly typed language and JavaScript is weakly typed, the JavaScript runtime engine converts argument values into the appropriate data types for the other language when you use LiveConnect. These conversions are described in the following sections:

JavaScript to Java Conversions

When you call a Java method and pass it parameters from JavaScript, the data types of the parameters you pass in are converted according to the rules described in the following sections:

The return values of methods of netscape.javascript.JSObject are always converted to instances of java.lang.Object. The rules for converting these return values are also described in these sections.

For example, if JSObject.eval returns a JavaScript number, you can find the rules for converting this number to an instance of java.lang.Object in "Number Values" on page 414.

Number Values

When you pass JavaScript number types as parameters to Java methods, Java converts the values according to the rules described in the following table:

Java parameter type Conversion rules

double

The exact value is transferred to Java without rounding and without a loss of magnitude or sign.

lava.lang.Double
java.lang.Object

A new instance of java.lang.Double is created, and the exact value is transferred to Java without rounding and without a loss of magnitude or sign.

float

byte
char
int
long
short

java.lang.String

Values are converted to strings. For example,

boolean

When a JavaScript number is passed as a parameter to a Java method which expects an instance of java.lang.String, the number is converted to a string. Use the == operator to compare the result of this conversion with other string values.

Boolean Values

When you pass JavaScript Boolean types as parameters to Java methods, Java converts the values according to the rules described in the following table:

Java parameter type Conversion rules

boolean

All values are converted directly to the Java equivalents.

lava.lang.Boolean
java.lang.Object

A new instance of java.lang.Boolean is created. Each parameter creates a new instance, not one instance with the same primitive value.

java.lang.String

Values are converted to strings. For example:

byte
char
double
float
int
long
short

When a JavaScript Boolean is passed as a parameter to a Java method which expects an instance of java.lang.String, the Boolean is converted to a string. Use the == operator to compare the result of this conversion with other string values.

String Values

When you pass JavaScript string types as parameters to Java methods, Java converts the values according to the rules described in the following table:

Java parameter type Conversion rules

lava.lang.String
java.lang.Object

A JavaScript string is converted to an instance of java.lang.String with an ASCII value.

byte
double
float
int
long
short

All values are converted to numbers as described in ECMA-262.

char

All values are converted to numbers.

boolean

Null Values

When you pass null JavaScript values as parameters to Java methods, Java converts the values according to the rules described in the following table:

Java parameter type Conversion rules

Any class
Any interface type

The value becomes null.

byte
char
double
float
int
long
short

The value becomes 0.

boolean

The value becomes false.

JavaArray and JavaObject objects

In most situations, when you pass a JavaScript JavaArray or JavaObject as a parameter to a Java method, Java simply unwraps the object; in a few situations, the object is coerced into another data type according to the rules described in the following table:

Java parameter type Conversion rules

Any interface or class that is assignment-compatible with the unwrapped object.

The object is unwrapped.

java.lang.String

The object is unwrapped, the toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String.

byte
char
double
float
int
long
short

The object is unwrapped, and either of the following situations occur:

boolean

The object is unwrapped and either of the following situations occur:

An interface or class is assignment-compatible with an unwrapped object if the unwrapped object is an instance of the Java parameter type. That is, the following statement must return true:

unwrappedObject instanceof parameterType

JavaClass objects

When you pass a JavaScript JavaClass object as a parameter to a Java method, Java converts the object according to the rules described in the following table:

Java parameter type Conversion rules

java.lang.Class

The object is unwrapped.

java.lang.JSObject
java.lang.Object

The JavaClass object is wrapped in a new instance of java.lang.JSObject.

java.lang.String

The object is unwrapped, the toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String.

boolean

The object is unwrapped and either of the following situations occur:

Other JavaScript objects

When you pass any other JavaScript object as a parameter to a Java method, Java converts the object according to the rules described in the following table:

Java parameter type Conversion rules

java.lang.JSObject
java.lang.Object

The object is wrapped in a new instance of java.lang.JSObject.

java.lang.String

The object is unwrapped, the toString method of the unwrapped Java object is called, and the result is returned as a new instance of java.lang.String.

byte
char
double
float
int
long
short

The object is converted to a value using the logic of the ToPrimitive operator described in ECMA-262. The PreferredType hint used with this operator is Number.

boolean

The object is unwrapped and either of the following situations occur:

Java to JavaScript Conversions

Values passed from Java to JavaScript are converted as follows:

Java String objects also correspond to JavaScript wrappers. If you call a JavaScript method that requires a JavaScript string and pass it this wrapper, you'll get an error. Instead, convert the wrapper to a JavaScript string by appending the empty string to it, as shown here:

var JavaString = JavaObj.methodThatReturnsAString();
var JavaScriptString = JavaString + "";

Table of Contents | Previous | Next | Index

Last Updated: 11/12/98 15:29:50

Copyright (c) 1998 Netscape Communications Corporation