Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run JavaScript code at server side Java code?

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?

like image 357
user223541 Avatar asked Jan 04 '10 13:01

user223541


People also ask

How do I run JavaScript on server-side?

Different ways to execute JavaScript from the server side in Web Form and AJAX frameworks. Calling a JavaScript function from the server is a relatively easy task. Just make sure that: The code is actually inserted on the page – the easiest way is to put a simple alert() and check if it is fired.

Can JavaScript be used as server-side script?

Server-side code can be written in any number of programming languages — examples of popular server-side web languages include PHP, Python, Ruby, C#, and JavaScript (NodeJS).

Can we run JavaScript on server?

Server-side JS is generally used to write the back-end logic of your web application; for instance, you can check to see if a user password matches the stored DB password. You can run Server-side JavaScript using any command-line interface.

Can we run JavaScript code in Java?

Java provides a command-line tool jjs which is used to execute JavaScript code. You can execute JavaScript code by using jjs command-line tool and by embedding into Java source code.


2 Answers

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 ...

like image 89
DomreiRoam Avatar answered Sep 21 '22 02:09

DomreiRoam


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);
}
like image 32
Manish Avatar answered Sep 22 '22 02:09

Manish