Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling java methods in javascript code [closed]

i created a java class content method return a String, my question is how to call this function in my javascript code to use the returned value from the java method. I want to call client-side Java code embedded in browser.

here is an exemple of what im talking about:

in my webpage i have a javascript code, here is some of it:

    function createChartControl(htmlDiv1)
{
    // Initialize Gantt data structures
    //project 1
    var parentTask1 = new GanttTaskInfo(1, "Old code review", new Date(2010, 5, 11), 208, 50, "");
......................

i want to create a java class content methods to provide data to this javascript function "GanttTaskInfo". for exemple function to get name, get id and date. well i think this time im clear :D i searched a way to call java methods in javascript, and i found applets as you said, but i think its not usefull to me. thanks again

like image 546
Nadya Nux Avatar asked Jul 11 '11 11:07

Nadya Nux


1 Answers

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>
like image 93
zacheusz Avatar answered Oct 14 '22 21:10

zacheusz