Evaluating javascript using a java code

后端 未结 3 873
我寻月下人不归
我寻月下人不归 2021-01-05 19:23

This might not be practical, but I have it as a task. I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the jav

3条回答
  •  甜味超标
    2021-01-05 20:13

    I've solved this in the past by creating a javascript function inside eval() and invoking it to get a result:

    import javax.script.*;
    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    try {
         // evaluate JavaScript code from String
         engine.eval("function sum(a,b){ return a + b;}");
         System.out.println(((Invocable) engine).invokeFunction("sum", new Object[]{10,20}));
    } catch (ScriptException ex) {
         Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
    }
    

    Note that the function name in invokeFunction (first argument) should match the one declared previously.

    Keep in mind that this might be dangerous. Do you have absolute control as to where the javascript code comes from? Otherwise a simple while(true){} could be pretty catastrophic for your server.

提交回复
热议问题