繁体   English   中英

如何使用Rhino JS从Javascript访问Java类(和函数)

[英]How to access Java classes (and functions) from Javascript using Rhino JS

我正在使用Rhino JS在Java上运行Javascript,问题是,有没有办法从Javascript访问Java类?

public void execute(Request request, Response response){
        String script = "function abc(x,y) {return x+y;}"; // example how to access the request and response object from within the script? 
        Context context = Context.enter();
        try {
            ScriptableObject scope = context.initStandardObjects();
            Scriptable that = context.newObject(scope);
            Function fct = context.compileFunction(scope, script, "script", 1, null);
            Object result = fct.call(context, scope, that, new Object[] { 2, 3 });
            System.out.println(Context.jsToJava(result, int.class));
        }
        finally {
            Context.exit();
        }
}

上面的代码示例非常简单,但是想法是如何从脚本内部访问请求和响应对象? 可能吗?

例:

function abc(request,response) {
    var body = request.body;
    response.body = body;
    return response;
}

ScriptableObject.defineProperty API可以在范围中定义属性。 javascript可以毫无问题地访问变量。

ScriptableObject scope = context.initStandardObjects();
Scriptable that = context.newObject(scope);
scope.defineProperty("req", request, ScriptableObject.READONLY);
scope.defineProperty("res", response, ScriptableObject.READONLY);
Object result = context.evaluateString(that, "function abc(request,response) {return response.body;}\n abc(req, res)", "script", 1, null);
System.out.println(Context.jsToJava(result, String.class));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM