在昨天弄清楚如何配置我的 Eclipse 项目以能够运行 JS 代码之后(如果您感兴趣:Build a JS server inside of Java for Google AppEngine),我有下一个与此主题相关的问题:我有一个 JS 文件和其中的一个函数.我需要在我的 Java 代码中运行该函数并在其中传递一个(Java 字符串)变量。我的文件非常基本,目前看起来像这样:
public class Com_feedic_readabilityServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
Context cx = ContextFactory.getGlobal().enterContext();
cx.setOptimizationLevel(-1);
cx.setLanguageVersion(Context.VERSION_1_5);
Global global = Main.getGlobal();
global.init(cx);
Main.processSource(cx, "server_js/js_init.js");
}
}
我现在需要做的是在 js_init.js
文件中调用函数 run()
。我该如何管理?
最佳答案
需要通过Binding对象来传递参数的值,如下:
package rhinodemo;
import java.util.Date;
import javax.script.*;
public class RhinoDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
Bindings bindings = engine.createBindings();
bindings.put("currentTime", new Date());
engine.eval(
"function run(x) { println('x=' + x); }" +
"run(currentTime);", bindings);
}
}
如果您希望 Java 代码调用名为 run()
的 Javascript 函数,则创建一个脚本,(a) 定义 run()
函数,以及 (b)调用这个函数,传递一个参数给它。然后,在Java端,需要创建一个Bindings对象,并设置这个参数的值bindings.put(currentTime, new Date())
。
关于java - 在Java中调用一个(Rhino)JS函数并传入一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3424315/