Run Javascript from Java

Last modified on August 1st, 2014 by Joe.

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);");
	}
}

Comments on "Run Javascript from Java"

  1. Anonymous says:

    learned something new thankx…

  2. babar ali says:

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

  3. Archana says:

    Please give some more example on this ….

  4. kalpesh says:

    very nice topic – thanks a lot

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

  6. Anonymous says:

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

  7. meen says:

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

  8. Mani says:

    Nice Joe. Keep up the GoodWork !!!

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

  10. Noorul says:

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

  11. Abhishek says:

    something new …
    gr8
    need to elaborate on it

  12. Anonymous says:

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

  13. abc says:

    How to pop up alert box using above packages?

  14. Java Learner says:

    When we need to excute javascript from java class?

  15. Anonymous says:

    Thanx so much sir…

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

  17. Tanuj says:

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

  18. Anonymous says:

    awesome……as always

  19. Punit says:

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

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

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

  22. Anonymous says:

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

  23. sam says:

    thank you Joe sir.really helpful ..

  24. Ganesh says:

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

  25. Thanumoorthy says:

    Thanks ..Today I learn new thing.

  26. Arivoli says:

    nice!! interesting…..

  27. Naveen says:

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

  28. Mamatha. says:

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

  29. phani says:

    Nice tutorial

    I learned new thing.

  30. Koustav Chatterjee says:

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

  31. Anonymous says:

    one new thing learnt!

  32. Anonymous says:

    New concept for me .

    Thanks
    Padmaja

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

  34. jagadeesh says:

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

  35. Rakesh L says:

    Nice Tutorial !! I learned something new !!

  36. ravinder says:

    good platform to learn new thing java

  37. Alok says:

    Hello Joe,

    Your expanations are always good.Thanks a lot.

  38. Pushpa says:

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

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

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

  41. Rishikesh says:

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

  42. sathish.pk says:

    nice tutorial..

  43. […] 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. […]

  44. […] 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 […]

Comments are closed for "Run Javascript from Java".