在Java中调用(Rhino)JS函数并传入变量

fb5*_*b55 2 javascript java rhino

昨天弄清楚如何配置我的Eclipse项目以便能够运行JS代码(如果你感兴趣:在Java内部为Google AppEngine构建一个JS服务器),我有下一个与此主题相关的问题:我有一个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");
 }
}
Run Code Online (Sandbox Code Playgroud)

我现在需要做的是调用该函数run()的内js_init.js-file.我该如何管理?

Ita*_*man 7

您需要通过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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果您希望Java代码调用调用的Javascript函数,run()那么创建一个脚本(a)定义run()函数,(b)调用此函数,并将参数传递给它.然后,在Java端,您需要创建一个Bindings对象并设置此参数的值bindings.put(currentTime, new Date()).