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;
}
asked Jun 20, 2016 at 7:08
quarks
35.7k82 gold badges311 silver badges555 bronze badges
1 Answer 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));
answered Jun 25, 2016 at 9:00
Beck Yang
3,0242 gold badges23 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default