Run Javascript from Java

This Java tutorial is to introduce the package javax.script.*. It can be used to execute scripting languages from within Java. Scripts can be executed within the JVM. Java provides a generic framework to hookup a scripting engine to run the scripts. Let us take JavaScript language and run an example. There are couple of important classes in this package and they are ScriptEngineManager and ScriptEngine.

ScriptEngineManager

ScriptEngineManager does two key functions. It does discovery of a script engine and stores data in context to allow it to be shared with programs. Data can be stored as key/value pairs and made available for all script engines. They should be considered as global data.

ScriptEngine

This is an interface available part of java api. This should be implemented separately for every scripting languages. For javascript in the Oracle JDK (from 1.6) by default an implementation is available. Apache commons provides a project Jakarta Bean Scripting Framework (BSF) which gives implementation for a several set of scripting languages like Python, TCL, NetRexx including javascript and lot more.

Example to Run Javascript in Java

import javax.script.*;

public class JavaJavaScript {
	public static void main(String args[]) throws ScriptException {
	    ScriptEngineManager manager = new ScriptEngineManager();
	    ScriptEngine engine = manager.getEngineByName("javascript");

	    engine.eval("var x = 10;");
	    engine.eval("var y = 20;");
	    engine.eval("var z = x + y;");
	    engine.eval("print (z);");
	}
}

This Core Java tutorial was added on 14/10/2012.

previous post: Android DatePicker

next post: How to call a C program from Java?

44 comments on “Run Javascript from Java

  1. hello
    i want to know that how to run the program in java CMD.

  2. Please give some more example on this ….

  3. Hi

    Nice to know about Javascript running from within the JVM. Could you please post some working examples on this to run and execute???

  4. Really something new concept for me but can you plz tell me where we can implement this concept in our web app?

  5. A new concept..happy to learn something new. can you provide us some more examples

  6. Hi Joe,

    I added following line and not able to execute..
    engine.eval(“alert(z)”);

    getting below exception…

    30Exception in thread “main” javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: “alert” is not defined. (#1) in at line number 1
    at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
    at com.sun.script.javascript.RhinoScriptEngine.eval(Unknown Source)
    at javax.script.AbstractScriptEngine.eval(Unknown Source)
    at com.kish.JavaJavaScript.main(JavaJavaScript.java:16)

    Any idea where am i going wrong…?

    • Hi,
      I repeated the same line after a year!
      engine.eval(“alert (z);”);

  7. Nice to get good information .
    Need some more examples for working javascript in java

  8. something new …
    gr8
    need to elaborate on it

  9. why java has given scripting support?.what could be the strong reason for that.

  10. How to pop up alert box using above packages?

  11. When we need to excute javascript from java class?

  12. It’s working same like as Sysdtem.out.println(). I ran in eclipse & it’s printing in console? I could not realize new thing in it as it claimed to be java script. So I can expect a new thing.

  13. awesome, just wanted to know, is any limitation of this, or i can use any js code with this?

  14. RESPONSE TO SOME OF THE ABOVE QUERIES:
    JDK by default includes Rhino which is a javascript engine written for java.

    It has only the core language implementation and does not contain objects or methods for manipulating HTML documents.

    alert() is a method of window and it is not available in the context you run the program.

    ————

    What is the use of providing support to scripting languages like javascript?

    We can write an entire program in a scripting language (javascript) and compile it to a java class file and run it in a jvm. By this we get all the power of a scripting language. I have personally used Groovy in extending/modifying underlying domain objects at runtime.

    —-
    This is just an introductory article. There is lot lot lot more to this.

  15. when i run this program i got a null pointer exception .
    engine has a null value.
    I used maven dependency is :

    org.apache.servicemix.specs
    org.apache.servicemix.specs.scripting-api-1.0
    1.1.0

    how can i fix this issue.
    thanks

    Thanks

  16. But java has all the functionality that Javascript provides then why we need Javascript in Java?
    I am confused!!

  17. Java has all the functionality that Javascript provides then why we need Javascript in Java?
    I too have the same question ?

  18. Really nice,
    learned some thing new instead of routine..
    Thank u

  19. Can you provide a real time scenario where exactly we need JavaScript in Java?

  20. why does not alert(javascript) work instead of print ?

  21. When I run the following code:
    Scriptable scope = cx.initStandardObjects();
    FileReader reader = new FileReader( “c:/temp/testing/scripts/person.js” );

    Object result = cx.evaluateReader(scope, reader, “c:/temp/testing/scripts/person.js”, 0, null);

    with IBM JDK 1.6, I got exception:
    org.mozilla.javascript.EcmaError: ReferenceError: “require” is not defined. (c:/temp/testing/scripts/person.js#19)

    I copied the js-14.jar to my jdk/jre/lib, jdk/jre/lib/ext but the exception still occurs.

    Any idea?

  22. its good to see new Java updates,,,its really I learned today new concepts ,,,thank for making this blog

  23. Hello Joe,

    Your expanations are always good.Thanks a lot.

  24. Can you please elaborate how can its beneficial to me. Means whats the advantage to use javascript in java.

  25. Could you please let me know how to call a java class from javascript function??

    and

    How to populate data from java file to html file to show on the front end??

    • Call Java from Javascript? Can you please give more detail, like what you are trying to achieve (the use case). Do you want information about AJAX?

      If I get your second question right, you should use a JSP to populate a value from a java bean into a html page.

  26. Pingback: Java 8 Features

  27. Pingback: Nashorn JavaScript Engine

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>