在 Java 中调用 (Rhino) JS 函数并传递一个变量
昨天弄清楚如何配置我的 Eclipse 项目以便能够运行 JS 代码(如果您感兴趣:在 Java for Google 中构建 JS 服务器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()
。我该如何处理?
after figuring out yesterday how to configure my Eclipse project to be able to run JS code (if your interested: Build a JS server inside of Java for Google AppEngine), I have the next question related to this topic: I got a JS file and a function within it. I need to run that function inside my Java code and to pass a (Java string) variable in it. My file is very basic, it currently looks like this:
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");
}
}
What I need to do now is calling the function run()
within the js_init.js
-file. How do I manage that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要通过 Binding 对象传递参数值,如下所示:
如果您希望 Java 代码调用名为
run()
的 Javascript 函数,则创建一个脚本,该脚本 (a) 定义 < code>run() 函数,并且 (b) 调用该函数,并向其传递一个参数。然后,在Java端,需要创建一个Bindings对象,并设置该参数的值bindings.put(currentTime, new Date())
。You need to pass the value of the parameter via a Binding object, as follows:
If you want your Java code to invoke a Javascript function called
run()
then create a script that (a) defines therun()
function and (b) calls this function, passing a parameter to it. Then, in the Java side, you need to create a Bindings object and set the value of this parameterbindings.put(currentTime, new Date())
.试试这个:
和js文件
out.println();
try this:
and js file
out.println(<text>);