Previous Contents Index Next |
iPlanet Web Server, Enterprise Edition Server-Side JavaScript Guide |
Chapter 14 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:
What Is LiveConnect?
For additional information on using LiveConnect, see the JavaScript technical notes on the iPlanet site, and also search for related information on the mozilla.org site.JavaScript to Java Communication
What Is LiveConnect?
LiveConnect lets you connect server-side JavaScript applications to Java components or classes on the server.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:
You can wrap your code as a Java object and use LiveConnect directly.
This chapter discusses using LiveConnect to access non-JavaScript code from JavaScript applications.You can wrap your code as a CORBA-compliant distributed object and use LiveConnect in association with an object request broker.
You can directly include external libraries in your application.
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" for information on setting CLASSPATH appropriately. LiveConnect works for both client-side and server-side JavaScript but has different capabilities appropriate to each environment.
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 JavaScript documentation at:
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 an 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 14-1    The LiveConnect Objects
Object
Description
A wrapped Java object, accessed from within JavaScript code.
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" 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")
For Netscape Enterprise Server 3.x, by default, the $NSHOME\js\samples directory is in the server's CLASSPATH. ($NSHOME is the directory in which the server was installed.) You can put your packages in this directory.
For iPlanet Web Server 4.x, you can choose to put your Java packages and classes in any directory. Make sure that the directory is specified in the jvm.classpath parameter in the jvm12.conf file.
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 objectsyou 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 methodsyou 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\plugins\samples\js\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" 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:
Verify that the user entered an ID for the bug. Enter the bug only in this case.
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."
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."
Display information to the client about the bug you have just stored.
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:
netscape.javascript.JSObject allows Java code to access JavaScript methods and properties.
These classes are delivered in either a .jar or a .zip file. See the Server-Side JavaScript Reference for more information about these classes.netscape.javascript.JSException allows Java code to handle JavaScript errors.
To access the LiveConnect classes, place the .jar or .zip file in the CLASSPATH of the JDK compiler in either of the following ways:
Create a CLASSPATH environment variable to specify the path and name of .jar or .zip file.
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:Specify the location of .jar or .zip file when you compile by using the -classpath command line parameter.
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" 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:
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" 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.
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\plugins\samples\js\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" for a description of the basic workings of this application and of its JavaScript code.
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.
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.
Create the Java Bug class, specifying its fields.
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.
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
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:
Number Values
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."
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:
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
A new instance of java.lang.Boolean is created. Each parameter creates a new instance, not one instance with the same primitive value.
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
A JavaScript string is converted to an instance of java.lang.String with an ASCII value.
All values are converted to numbers as described in ECMA-262.
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
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:
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:
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 to JavaScript Conversions
Values passed from Java to JavaScript are converted as follows:
Java byte, char, short, int, long, float, and double are converted to JavaScript numbers.
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:A Java boolean is converted to a JavaScript boolean.
An object of class netscape.javascript.JSObject is converted to the original JavaScript object.
Java arrays are converted to a JavaScript pseudo-Array object; this object behaves just like a JavaScript Array object: you can access it with the syntax arrayName[index] (where index is an integer), and determine its length with arrayName.length.
A Java object of any other class is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object:
Converting this wrapper to a string calls the toString method on the original object.
Converting to a number calls the doubleValue method, if possible, and fails otherwise.
Converting to a boolean calls the booleanValue method, if possible, and fails otherwise.
- Note that instances of java.lang.Double and java.lang.Integer are converted to JavaScript objects, not to JavaScript numbers. Similarly, instances of java.lang.String are also converted to JavaScript objects, not to JavaScript strings.
var JavaString = JavaObj.methodThatReturnsAString();
var JavaScriptString = JavaString + "";
Previous Contents Index Next
Copyright © 2000 Sun Microsystems, Inc. Some preexisting portions Copyright © 2000 Netscape Communications Corp. All rights reserved.
Last Updated August 09, 2000