172 CHAPTER 9 SCRIPTING AND JSR 223
174 CHAPTER 9 SCRIPTING AND JSR 223 To have a scripting engine evaluate an expression, you would use one of the six versions of its eval() method, all of which can throw a ScriptException if there are errors in the script: public Object eval(String script) public Object eval(Reader reader) public Object eval(String script, ScriptContext context) public Object eval(Reader reader, ScriptContext context) public Object eval(String script, Bindings bindings) public Object eval(Reader reader, Bindings bindings) The script to evaluate can either be in the form of a String object or come from a Reader stream. The ScriptContext allows you to specify the scope of any Bindings objects, as well as get input, output, and error streams. There are two predefined context scopes: ScriptContext.GLOBAL_SCOPE and ScriptContext.ENGINE_SCOPE. The Bindings objects are just a mapping from a String name to a Java instance, with global scope meaning that names are shared across all engines. Tip To set the default context for an engine, for when a ScriptContext isn t passed into eval(), call the setContext() method of ScriptEngine. Listing 9-2 demonstrates the evaluation of a simple JavaScript expression from a string. It gets the current hour and displays an appropriate message. The JavaScript code itself is in bold. Listing 9-2. Evaluating JavaScript import javax.script.*; import java.io.*; public class RunJavaScript { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); try { Double hour = (Double)engine.eval(
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services