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.

«

»

Comments on "Run Javascript from Java"

  1. […] can use the ScriptEngine API to invoke and run JavaScript via Nashorn. Earlier we have seen a tutorial to run JavaScript in Java. It uses the javax.script package. While instantiating the ScriptEngine we need to pass […]

  2. […] Nashorn is a brand new JavaScript engine provided along with the Java 8 release. Using this we can develop standalone JavaScript applications in Java. Pre Java 8, we got JDK with a JavaScript engine based on Rhino. It is a developed from scratch. It will provide better compatibility with ECMA normalized JavaScript specification and better performance than Rhino. Already we have seen a tutorial to run Javascript in Java using the ScriptEngineManager. […]

  3. sathish.pk says:

    nice tutorial..

  4. Janardhan says:

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

    • Joe says:

      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.

  5. Pushpa says:

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

  6. Alok says:

    Hello Joe,

    Your expanations are always good.Thanks a lot.

  7. ravinder says:

    good platform to learn new thing java

  8. Rakesh L says:

    Nice Tutorial !! I learned something new !!

  9. jagadeesh says:

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

  10. Thuy says:

    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?

  11. Anonymous says:

    New concept for me .

    Thanks
    Padmaja

  12. Anonymous says:

    one new thing learnt!

  13. Koustav Chatterjee says:

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

  14. phani says:

    Nice tutorial

    I learned new thing.

  15. Mamatha. says:

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

  16. Naveen says:

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

  17. Arivoli says:

    nice!! interesting…..

  18. Thanumoorthy says:

    Thanks ..Today I learn new thing.

  19. Ganesh says:

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

  20. sam says:

    thank you Joe sir.really helpful ..

  21. Anonymous says:

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

  22. Jitendra says:

    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

  23. Joe says:

    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.

  24. Punit says:

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

  25. Anonymous says:

    awesome……as always

  26. Tanuj says:

    LOve d work.. well done.. thnks..!!!

  27. Ayaz Uddin says:

    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.

  28. Anonymous says:

    Thanx so much sir…

  29. Java Learner says:

    When we need to excute javascript from java class?

  30. abc says:

    How to pop up alert box using above packages?

  31. Anonymous says:

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

  32. Abhishek says:

    something new …
    gr8
    need to elaborate on it

  33. Noorul says:

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

  34. Kishore says:

    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…?

  35. Mani says:

    Nice Joe. Keep up the GoodWork !!!

  36. meen says:

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

  37. Anonymous says:

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

  38. Sanjeev says:

    Hi

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

  39. kalpesh says:

    very nice topic – thanks a lot

  40. Archana says:

    Please give some more example on this ….

  41. babar ali says:

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

  42. Anonymous says:

    learned something new thankx…

Your Comment