How do you use java files in Coldfusion

2019-01-14 23:47发布

问题:

I need to import a java file into a coldfusion 8 page e.g. :

public class Hello 
{ 
    public String testJava() 
    { 
    return "Hello Java!!"; 
    } 
}

In Coldfusion I have the following code:

<cfscript>
   helloWorld = CreateObject("java","Hello");
   helloTest = helloWorld.testJava();
</cfscript>

I then receive the error

Object Instantiation Exception. Class not found: Hello

In my Coldfusion server Java Virtual Machine Path is set to 'C:/ColdFusion8/runtime/jre', So this is where I have put my java file, is this correct? Should I put a .java, .class or .jar there?

Does the file name need to be consistent with class name?

Does anyone have working sample code for something similar I can try?

回答1:

You need to put the files on the the ColdFusion JVM's classpath, not in its JRE dir.

As a rule, if you have a jar file, put it in the instances's WEB-INF/lib dir, if it's just a class, put it in the WEB-INF/classes dir, eg: for me the latter would be C:\apps\adobe\ColdFusion\11\full\cfusion\wwwroot\WEB-INF\classes, where C:\apps\adobe\ColdFusion\11\full\ is where I installed CF, and cfusion is the name of the instance.



回答2:

Does the file name need to be consistent with class name?

Do you mean the name of the .java file? Yes, but that is a java requirement. If your class is named "Hello", then your source file must be named "Hello.java" or it will not compile. When you compile the source code, the java compiler will generate a file named "Hello.class". Copy that file into the CF class path. The convention is to place individual .class files inside WEB-INF\classes and jar files inside WEB-INF\lib, as Adam mentioned. Note, you must restart the CF server for it to detect the new class(es)

After restarting, you will be able to create an instance of the class. However, be sure to use the correct class name in your createObject statement. It should be "Hello" - not "Test". Also, unlike most things in CF, the class name is cAsE sEnSiTive.

<cfscript>
    helloWorld = CreateObject("java","Hello");
    helloTest = helloWorld.testJava();
    WriteDump( helloTest );
</cfscript>


Update: That said, using individual class files is fine for testing purposes. However, you would normally package classes into a .jar file instead. With jar files, the file name is irrelevant. Only the internal path to the class matters. If your class resides in a package, you must include the package name as well. For example, if your Hello class resides in a package named com.utilities, the full path would be:

 helloTest  = createObject("java", "com.utilities.Hello");

In terms of the class path, usage is the same. Just place the jar file in the CF class path ie WEB-INF\lib and restart. As Raymond mentioned in the comments, for CF10+ see Specifying custom Java library path in the Application.cfc without dynamic loading.