0

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

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.