Thursday, June 6, 2013

Execute Javascript from Java

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.

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.
You have to be aware that the servlet runs on the server, not on the client computer. If you use the scripting API to run JavaScript code from your servlet, then it's going to run on the server, and not the client. If your goal is to display a message box on the client's computer, then trying to run JavaScript code on the server doesn't make sense.

Another way
  •  // JavaScript code in a String  
  •         String script = "function hello(name) { print('Hello, ' + name); }";  
  •         // evaluate script  
  •         engine.eval(script);  
  •   
  •         // javax.script.Invocable is an optional interface.  
  •         // Check whether your script engine implements or not!  
  •         // Note that the JavaScript engine implements Invocable interface.  
  •         Invocable inv = (Invocable) engine;  
  •   
  •         // invoke the global function named "hello"  
  •         inv.invokeFunction("hello""Scripting!!" ); 

Source:
http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/

0 comments:

Post a Comment