Search code examples
javajavascripthtmlnashorn

Use Nashorn in html's javascript file


I'm trying to access my Java classes from an html file. The problem is that javascript doesn't seem to have Java defined on it, since it's js and not jjs, and I keep having the Uncaught ReferenceError: Java is not defined.

How can I use Nashorn in my html file.

Imagine the following file structure:

index.html

<!DOCTYPE html>
<html>
<head>
    <title>index</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="img/transparent_logo.png" type="image/x-icon" />
    <script src="script.js" type="text/javascript"></script>
</head>
<body>
    <button onclick="read_java()">click me!</button>
    <div id="response"></div>
</body>
</html>

script.js

var class1 = Java.type('src.domain.Driver');
function read_java(){
    var parameter="hello";
    var response=class1.random_number(parameter);
    console.log(response);
}

Driver.java (on /src/domain/Driver.java)

public int random_number(String name) {
    if (name=="hello")
        return 1;
    else 
        return 2;
    return 0;
}

I have already done a lot of research but I wasn't able to find any tutorial related to html so I'm completly lost. Could you tell me how can I execute this simple test, with this I should be able to continue with my app. Thanks!


Solution

  • Java classes are not available inside the browser (unless you are using an Applet and could run Nashorn inside there, which is crazy of course ;)

    What are you trying to achieve?