quarks
quarks

Reputation: 35276

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

I am using Rhino JS for running Javascript on Java, the question, is there a way to access Java classes from Javascript?

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();
        }
}

The code example above is very simplistic, but the idea is how to access the request and response object from within the script? Is it possible?

Example:

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

Upvotes: 0

Views: 548

Answers (1)

Beck Yang
Beck Yang

Reputation: 3024

The ScriptableObject.defineProperty API can define a property in the scope. The javascript access the variable without problem.

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));

Upvotes: 1

Related Questions