日期:2014-05-16 浏览次数:20394 次
package com.chen.java; import java.io.File; import java.io.FileReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import com.chen.interfaces.Greeter; /** * 这个场景的代码用于在web容器中调用js中定义的方法。Greeter 是java接口类,和js中定义的方法在名称,参数和返回值上保持一致 * @author Administrator * */ public class TestScript { public static void main(String[] args) { String url = TestScript.class.getResource("/").getPath(); String str = null; try { str = URLDecoder.decode(url.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String path = new File(str).getParent() + File.separator + "js" + File.separator + "test.js"; try { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval(new FileReader(path)); Greeter g = ((Invocable) engine).getInterface(Greeter.class); System.out.println("result = " + g.greet("androidla")); } catch (Exception e) { e.printStackTrace(); } } }
package com.chen.interfaces; public interface Greeter { String greet(String whom); }
function greet(name) { return "I'm write in JavaScript, hello, " + name; }
result = I'm write in JavaScript, hello, androidla