CLASSPATH
. For information on setting up CLASSPATH
, see the Programmer's Guide to Servlets. 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.5.1/3.6: Notes for Java Programmers1. For other information on LiveConnect, see the DevEdge Library2.
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.
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.
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 11You 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);
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
.
JavaArray
. For example, the following code creates the JavaArray
x
with ten elements of type int:
theInt = java.lang.Class.forName("java.lang.Integer")Like the JavaScript
x = java.lang.reflect.Array.newInstance(theInt, 10)
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.
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)
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)
$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," 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.The steps in this code are:
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>");
}
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."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."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.netscape.javascript.JSException
allows Java code to handle JavaScript errors.
These classes are delivered in either a .jar or a .zip file. See the Server-Side JavaScript Reference for more information about these classes.
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.jarFor more information about
CLASSPATH
, see the
Administrator's Guide.
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.
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
.
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.*;Notice that the
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");
}
}
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 toTo get a better sense of howgetMember
inside atry...catch
statement to handle errors of typeJSException
. See "Handling JavaScript Exceptions in Java," for more information.
getMember
works, look at the definition of the custom JavaScript object Dog
:
function Dog(breed,color,sex) {You can create a JavaScript instance of
this.breed = breed
this.color = color
this.sex = sex
}
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
.
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 {In this example, the
global.eval("foo.bar = 999;");
} catch (Exception e) {
if (e instanceof JSException) {
jsCodeFailed()";
} else {
otherCodeFailed();
}
}
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.
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.
JSObject
, nor can it use writeHttpOutput
, because this method requires access to the HTTP response buffer.
$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," 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.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.
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();
} }
netscape.javascript
and netscape.server.serverenv
packages. If you omit this step, you cannot use JavaScript objects.Bug
class, specifying its fields.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.toString
method. This is a standard method for a Java object that returns a string representation of the fields of the object.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."
Java parameter type |
Conversion rules
The exact value is transferred to Java without rounding and without a loss of magnitude or sign.
|
|
|
|
| |
---|
java.lang.String
, the number is converted to a string. Use the == operator to compare the result of this conversion with other string values.
Java parameter type |
Conversion rules
|
|
|
| |
---|
java.lang.String
, the Boolean is converted to a string. Use the == operator to compare the result of this conversion with other string values.
Java parameter type |
Conversion rules
A JavaScript string is converted to an instance of All values are converted to numbers as described in ECMA-262.
|
| |
---|
Java parameter type |
Conversion rules
|
|
| |
---|
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:
unwrappedObject instanceof parameterType
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
|
The
| The object is unwrapped and either of the following situations occur: |
---|
netscape.javascript.JSObject
is converted to the original JavaScript object.Array
object: you can access it with the syntax arrayName[index]
(where index
is an integer), and determine its length with arrayName.length
.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 + "";
Last Updated: 09/29/99 18:02:00