views:

148

answers:

1

Hi,

after figuring out yesterday how to configure my Eclipse project to be able to run JS code (if your interested: http://stackoverflow.com/questions/3417958/), 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?

+1  A: 

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()).

Itay
I got the error "println not defined". How do I pass content evaluated by Rhino back to a variable (remember, I'm using a JS-server)?
FB55