Archive
Execute Javascript from Java
After a small gap,I am back to here for share something to you all.A week before i have stuck with execute javascript from java.I google it for this.Finally i found my way to achieve this.
Java provides the way to execute JavaScript also.The solution is come along with ScriptEngineManager.This article deals the same.
The ScriptEngineManager comes along with the package javax.script.
This is a relatively small, simple API. A ScriptEngineManager object can discover script engines through the jar file service discovery mechanism. It can also instantiate ScriptEngine objects that interpret scripts written in a specific scripting language. The simplest way to use the scripting API is as follows:
- Create a ScriptEngineManager object.
- Get a ScriptEngine object from the manager.
- Evaluate script using the ScriptEngine’s eval methods.
Now we look at the sample code.
import javax.script.*;
public class ExecuteScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from String
engine.eval("print('Welocme to java world')");
}
}
Executing a Script from .js File:
In this example, we can execute JavaScript which is from .js file.This can be achieved by the eval method of ScriptEngine Class.
The eval method have the FileReader object as argument.
we can create the ScriptEngineManager and get the ScriptEngine from the above code(line 4-7).
Then we add the eval method which is used to execute script from .js file.
// evaluate JavaScript code from given file
engine.eval(new java.io.FileReader("welcome.js"));
Let us assume that we have the file named “welcome.js” with the following text:
println("Welcome to java world");
If we will run the code,this yields the output as
Welcome to java world.
I hopes this helps.Then Go ahead to execute your JavaScript by using your java code.Before that,if you feel it useful,leave your foot prints here[Comments].

Recent Comments