CHAPTER 9 SCRIPTING AND JSR 223 175
176 CHAPTER 9 SCRIPTING AND JSR 223 public class FlipBindings { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); if (args.length != 1) { System.err.println(”Please pass name on command line”); System.exit(-1); } try { engine.put(”name”, args[0]); engine.eval( “var output = ‘’;” + “for (i = 0; i <= name.length; i++) {" + " output = name.charAt(i) + output" + "}"); String name = (String)engine.get("output"); Console console = System.console(); console.printf("Reversed: %s%n", name); } catch (ScriptException e) { System.err.println(e); } } } Passing in the book name to the program shows the reversed title: > java FlipBindings “Java 6 Platform Revealed” Reversed: delaeveR mroftalP 6 avaJ Note Errors in the JavaScript source are handled by the caught ScriptException. It is best to at least print out this exception, as it will reveal errors in the script code. You can also get the file name, line number, and column number in which the error happened.
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services