Out of the box, JDK 6 comes bundled with the engine called Mozilla Rhino, which is able to evaluate
JavaScript programs. This section will give you an introduction to the JSR-223 support in JDK 6.
In JDK 6, the scripting support classes reside in the package javax.script. First let's develop a
simple program to retrieve the list of script engines. Listing 22-1 shows the class content.
Listing 22-1. Listing Scripting Engines
package com.apress.prospring3.ch22.jsr223;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ListScriptEngines {
public static void main(String[] args) {
ScriptEngineManager mgr = new ScriptEngineManager();
for (ScriptEngineFactory factory : mgr.getEngineFactories()) {
String engineName= factory.getEngineName();
String languageName = factory.getLanguageName();
String version = factory.getLanguageVersion();
System.out.println("Engine name: " + engineName + " Language: " + languageName + "
version: " + version);
}
}
}
In Listing 22-1, an instance of the ScriptEngineManager class is created, which will discover and
maintain a list of engines (in other words, classes implementing the javax.script.ScriptEngine
interface) from the classpath. Then, a list of ScriptEngineFactory interfaces is retrieved by calling the
ScriptEngineManager.getEngineFactories() method. The ScriptEngineFactory interface is used to
describe and instantiate script engines. From each ScriptEngineFactory interface, information about
the scripting language support can be retrieved. Running the program will produce the following output
in the console:
Engine name: Groovy Scripting Engine Language: Groovy version: 1.8.4
Engine name: Mozilla Rhino Language: ECMAScript version: 1.6
As shown in the output, two script engines are detected. The first one is the Groovy engine, since we
converted the project to a Groovy project and added the Groovy libraries. The other one is ECMAScript,
which is JavaScript.
Let's write a simple program to evaluate a basic JavaScript expression. The program is shown in
Listing 22-2.
Listing 22-2. Evaluates a JavaScript Expression
package com.apress.prospring3.ch22.jsr223;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptTest {
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home