How to Use JavaScript in Java

How can I use JavaScript in Java?

Rhino is what you are looking for.

Rhino is an open-source implementation of JavaScript written entirely
in Java. It is typically embedded into Java applications to provide
scripting to end users.

Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.

Update 2022: Nashorn was deprecated in Java 11, then eventually removed in Java 15.

Call external javascript functions from java code

Use ScriptEngine.eval(java.io.Reader) to read the script

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

Javascript inside a java code

you can return a string from your code and you can declare html tags as the returning String. I will suggest a sample code.

        @GET
@Path("/")
@Produces("text/html")
public String getStatus(@Context HttpServletRequest request) {
return "<html><head><script>put your java script code here...</script></head></html>"
}

Best way to create readable Javascript in Java for adding to html page

I think you should write your JavaScript in .js files. Include them either via script().withScr("/path/to/file.js") (if the file is hosted), or via scriptWithInlineFile_min("/path/to/file.js") (if you want to read the file from the classpath/file-system).

How can I continue to use Javascript in Java 15 onwards

You can use a standalone version of Nashorn: https://github.com/openjdk/nashorn.

Nashorn is a JPMS module, so make sure it and its transitive
dependencies (Nashorn depends on several ASM JARs) are on your
application's module path, or appropriately added to a module layer,
or otherwise configured as modules.

While standalone Nashorn is primarily meant to be used with Java 15
and later versions, it can also be used with Java versions 11 to 14

that have a built-in version of Nashorn too. See this page for details
on use when both versions are present.

Calling Java from JavaScript and vice-versa why?

In web application development (which is the usual scenario where Java and JavaScript interact):

there are 2 places where you can make the server and client side languages interact with each other:

  1. At rendering time, this is, when generating the HTML output to the user.

  2. At runtime, this is, when the HTML has been generated and it is at client side (e.g. browser client).

For the first case, let's say we have a Servlet that adds an attribute to the request and forward to a new (JSP) view. This is an example of the servlet:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
// Prepare messages.
request.setAttribute("name", name);
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}

Then in your view (hello.jsp file inside WEB-INF folder), you have a code like this:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<script>
function changeName(var newName) {
document.getElementById('divName').innerHtml = 'Hello ' + newName;
}
window.onload = function () {
changeName('${name}');
}
</script>
</head>
<body>
<div id="divName">
</div>
<form id="name" action="hello">
Change name to: <input type="text" name="name" />
<br />
<input type="text" value="Change the name" />
</form>
</body>
</html>

By using this approach, we can communicate Java generates variables (NEVER SCRIPTLETS) directly to JavaScript when rendering the view. So we can access to Java page, request, session and context attributes only when creating the HTML that is going to the client.

Note that if you want to re-execute this Java code, you should fire a new request to the server in order to execute the Java code. This is where ajax come handy.

Ajax lets you communicate with the server side asynchronously, the server will prepare a response for your request, and then in client side you will define how to use it. For this purpose, it is better to use a common format for the communication. The most preferred format nowadays is JSON. Ajax interactions to servlet is widely covered here: How to use Servlets and Ajax? (no need to reinvent the wheel in this post).


In standalone or mobile applications:

Java will run on the client machine. Note that here Java can execute JavaScript code through a JavaScript engine like Rhino or nashorn. This is useful when you have lot of functionalities already written in javascript (like an external library) and do not want to migrate all the code to Java. You can just use ScriptEngineManager and StringEngine classes to execute the code in JavaScript in your Java application. A real-world example of using JavaScript in a Java application is Pentaho Kettle, written in Java, that allows applying transformations to your code through JavaScript scripts.

More info on Nashorn:

  • Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM

how to use java to get a js file and execute it and then get the result

There's three steps to this process:

  1. Fetch the JS file from the server.
  2. Execute some JS function from the file.
  3. Extract the result.

The first step is fairly simple, there are lots of HTTP libraries in Java that will do this - you effectively want to emulate the simple functionality of something like wget or curl. The exact manner in which you do this will vary depending on what format you want the JS file in for the next step, but the process to get hold of the byte stream is straightforward.

The second step will require executing the JS in a Javascript engine. Java itself cannot interpret Javascript, so you'd need to obtain an engine to run it in - Rhino is a common choice for this. Since you'd need to run this outside of Java, you'll likely have to spawn a process for execution in Rhino using ProcessBuilder. Additionally, depending on the format of the Javascript you might need to create your own "wrapper" javascript that functions like a main class in Java and calls the method in question.

Finally you need to get the result out - obviously you don't have direct access to JavaScript objects from your Java program. The easiest way is going to be for the JS program to print the result to standard out (possibly serialising as something like JSON depending on the complexity of the object), which is being streamed directly to your Java app due to the way you launched the Rhino process. This could be another job for your JS wrapper script, if any. Otherwise, if the JS function has observable side effects (creates a file/modifies a database) then you'll be able to query those directly from Java.

Job done.

I hope you realise this question is far too vague to get full answers. Asking the public to design an entire system goes beyond the point where you'll get useful, actionable responses.



Related Topics



Leave a reply



Submit