简体   繁体   中英

How to call a java class methods from java script which will be used in html page?

I want to use some java object value inside my java script .Is there any way to do that. After searching in web i found that oracle has some documentation on that

http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html

But I tried same thing in my html web pages it seems that web page results parsing error and did not display anything.

Note-Here I donot want to use jsp servelet.Iam very much know to this fact that javascript is a client side technology but please confirm me if there is any way possible to call Please have a look what i have tried so far.

<script type="text/javascript">
<!--

importPackage(java.lang);
// Import the java.lang.String class
importClass(java.lang.String);

var StringArray = Java.type("java.lang.String[]");
var a = new StringArray(5);

// Set the value of the first element
a[0] = "Scripting is great!";
// Print the length of the array
print(a.length);
document.write(a.length);


// You can include version to along with any above condition.
document.write("<br /> Browser version info : " + version );
//-->
</script>

The code you have posted is Rhino or Nashorn Javascript engine for Java. It's called from Java. It doesn't support document object. This code can be used in desktop or server applications which don't know anything about a browser.

Here is described how to imitate document object to let its usage in Nashorn. It's written mainly for porting reasons. Eg if you have many scripts previously written for browser (which contain document object) and now you need to port these scripts to desktop application then you're able to imitate that object.

If you'd like to use Nashorn in a browser instead of desktop application, you can pass real document object to Java applet and then pass it to Nashorn as described in that link. You need such a schema of calling: Browser (Javascript) -> Applet (Java) -> Nashorn (Javascript). It's strange, isn't it? And redundant.

So, the simple way is just to create an applet and interact with it. Take a look at this approach . But there will be no importPackage methods. You'll have to write Java code in applet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM