开发者

Call a (Rhino) JS function in Java and pass a variable in

开发者 https://www.devze.com 2023-01-10 07:16 出处:网络
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

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 fil开发者_如何学JAVAe 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?


You need to pass the value of the parameter via a Binding object, as follows:

  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);
    }
  }

If you want your Java code to invoke a Javascript function called run() then create a script that (a) defines the run() 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 parameter bindings.put(currentTime, new Date()).


try this:

Object jsOut = Context.javaToJS(System.out, scope);
ScriptableObject.putProperty(scope, "out", jsOut);

and js file out.println(<text>);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号