簡體   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