作者:x将臣x | 来源:互联网 | 2023-02-11 13:01
我将以下代码与Rhino
Java中的Javascript引擎一起使用:
@Test
public void testRhino() throws ScriptException {
final ScriptEngineManager factory = new ScriptEngineManager();
final ScriptEngine engine = factory.getEngineByName("rhino");
final String raw = "I am the raw value injected";
final ScriptContext ctx = new SimpleScriptContext();
ctx.setAttribute("raw", raw, ScriptContext.ENGINE_SCOPE);
String script = "var result = 'I am a result';";
script += "java.lang.System.out.println(raw);";
script += "'I am a returned value';";
final Object res = engine.eval(script, ctx);
System.out.println(ctx.getAttribute("result"));
System.out.println(res);
}
脚本的输出(使用Rhino
)为:
I am the raw value injected
I am a result
I am a returned value
在Nashorn
Javascript引擎中,我没有任何价值result
:
@Test
public void testNashorn() throws ScriptException {
final ScriptEngineManager factory = new ScriptEngineManager();
final ScriptEngine engine = factory.getEngineByName("nashorn");
final String raw = "I am the raw value injected";
final ScriptContext ctx = new SimpleScriptContext();
ctx.setAttribute("raw", raw, ScriptContext.ENGINE_SCOPE);
String script = "var result = 'I am a result';";
script += "java.lang.System.out.println(raw);";
script += "'I am a returned value';";
final Object res = engine.eval(script, ctx);
System.out.println(ctx.getAttribute("result"));
System.out.println(res);
}
退货
I am the raw value injected
null
I am a returned value
如何使用引擎访问result
变量的值?ScriptContext
nashorn
1> A. Sundarara..:
如果使用ScriptEngine.createEngine API创建ENGINE_SCOPE绑定,它将按预期工作:
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
final ScriptEngineManager factory = new ScriptEngineManager();
final ScriptEngine engine = factory.getEngineByName("nashorn");
final String raw = "I am the raw value injected";
final ScriptContext ctx = new SimpleScriptContext();
// **This is the inserted line**
ctx.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
ctx.setAttribute("raw", raw, ScriptContext.ENGINE_SCOPE);
String script = "var result = 'I am a result';";
script += "java.lang.System.out.println(raw);";
script += "'I am a returned value';";
final Object res = engine.eval(script, ctx);
System.out.println(ctx.getAttribute("result"));
System.out.println(res);
}
}