13

I want to run JavaScript code at the server side. I want to manipulate result returned by JavaScript inside my Java code. How can it be done?

1
  • This question is similar, but has different answers. Commented Jul 7, 2015 at 19:16

6 Answers 6

17

The start is clearly to look into rhino.

I think you will find this 3 links very useful

  1. JavaScript EE, Part 1: Run JavaScript files on the server side
  2. JavaScript EE, Part 2: Call remote JavaScript functions with Ajax
  3. JavaScript EE, Part 3: Use Java scripting API with JSP

You can also have a look to helma

Helma is a server-side Javascript environment and web application framework for fast and efficient scripting and serving of your websites and Internet applications.

Helma is written in Java and employs Javascript for its server-side scripting environment ...

Sign up to request clarification or add additional context in comments.

Comments

10

The other answers are correct that if you want to execute Javascript on the server side, you'd need to evaluate it in the context of a JS runtime.

However, I'm not convinced that this is exactly what you're asking. I think there may be a chance that you want to run some "typical" JS functionality that relates to how the page is displayed on the client's machine or interacted with on the client - and that will not be possible to run on the server side.

As a concrete examples:

  1. If you want to run some kind of algorithm in JS without porting it to Java - say, you have some opaque Javascript code that generates a particular sequence given a seed - this would work fine if you run it on Rhino on the server.
  2. If you want to invoke a Javascript function while creating the page, rather than while it's running - say, to get the user's colour depth/screen resolution and change how the page is generated - then this will not be possible from the server, as there is no client at this point to query.

Broadly speaking, any Javascript that involves document or navigator or even any elements of the page itself, is likely to fall into the latter category.

If you really need to get information about the client environment in order to control how the page is rendered, this must be extracted from the client on the previous page, and encoded into the request (as query parameters or form data). These parameters can then be read directly on the server and used to control the output.

Remember that when your code is running on the server side, you're creating a page (ultimately a bunch of HTML, CSS and JS) that will be sent to the client once it's done - at this point there is no client yet and so you can't interact with them.

Apologies if I've got the wrong end of the stick on this one, but this type of question is typically asked by people who haven't grasped the client/server separation.

Comments

3

You need a JS runtime inside of a Java runtime. One way to do this is Rhino

Comments

2

You execute the JavaScript with Rhino, a JavaScript library for Java.

Comments

2

You can use RHINO or NASHORN.

public class RhinoApp {
private String simpleAdd = "var z=9; z*=9";

public void runJavaScript() {
    Context jsCx = Context.enter();
    Context.getCurrentContext().setOptimizationLevel(-1);
    ScriptableObject scope = jsCx.initStandardObjects();
    Object result = jsCx.evaluateString(scope, simpleAdd , "formula", 0, null);
    Context.exit();
    System.out.println(result);
}

1 Comment

Nice answer. But you can improve it. Could you add imports and maven dependencies, so it will be copy-paste driven!
0

This example should clearly state how to load, evaluate and execute a Javascript function in Java:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
URI source_js = JavascriptExecutor.class.getResource("/file.js").toURI();
String source_text = Files.readAllLines(Paths.get(source_js)).stream().collect(Collectors.joining("\n"));
engine.eval(source_text);
Invocable inv = (Invocable) engine;
Object returnValue = inv.invokeFunction("functionJsName", "functionJsParameter");
System.out.println(returnValue.toString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.