Scripting in ASP with Java
I’m working on a project right now that involves a store written in Java using Struts and a sister site written in ASP. One of the features of the store requires that the sister site use some logic written in Java, which you might think is impossible. Turns out (doesn’t it always?) that you can quite easily use simple Java methods and objects within ASP from VBScript. I found two articles (and really only 2) that introduced the use of a simple Java class from ASP (which you can read here and here). Here’s a Hello World example:
package org.mycompany;
public class TestClass {
public String sayHello(String name) {
return "Hello " + name;
}
}
compile this and then you save the resulting class file to:
%Win%/Java/TrustLib/%package%/%classname%.class
So the above example would result in a file saved as:
%Win%/Java/TrustLib/org/mycompany/TestClass.class
From ASP, you can then use the following syntax:
Dim obj
set obj = GetObject("java:org.comcompany.TestClass")
result = obj.sayHello("Aaron Johnson");
Response.Write(result)
set obj = nothing
Couple of items of note:
a) the use of what Microsoft calls a “Java Moniker” allows you to use a Java class without first registering it with the system, which is nice (so you got that going for ya),
b) just like a servlet container, if you make changes to the Java class file while the application is running, you must restart the container, which in this case is IIS,
c) you must (as I mentioned before) make sure to place the compiled class file in the appropriately named subdirectory of %Win%/Java/TrustLib/, where %Win% is usually C:\windows\ or C:\winnt\,
d) you can’t use static methods in your Java class if you want to be able to call those methods from VBScript. It appears (from my quick attempts) that the VBScript engine first creates an object using the default constructor and then calls the given method on that instance. Modifiying the method to be static resulted in a runtime error, and finally
e) your code must work in the Microsoft JVM (I think), which isn’t being supported past September 2004.
15 Comments