JavaScript脚本引擎不是';t在Google App Engine for Java(GAE/J)中工作
我遇到一个问题,当我尝试使用ScriptEngine eval时,总是返回0值。通过使用Logger,我能够确定是否生成了NullPointerException。进一步检查之后,GAE似乎并不总是返回有效的脚本引擎(如果有的话),因为当您尝试使用它时,它会抛出一个异常 我的代码如下所示:JavaScript脚本引擎不是';t在Google App Engine for Java(GAE/J)中工作,java,google-app-engine,nullpointerexception,scriptengine,Java,Google App Engine,Nullpointerexception,Scriptengine,我遇到一个问题,当我尝试使用ScriptEngine eval时,总是返回0值。通过使用Logger,我能够确定是否生成了NullPointerException。进一步检查之后,GAE似乎并不总是返回有效的脚本引擎(如果有的话),因为当您尝试使用它时,它会抛出一个异常 我的代码如下所示: public double myEval(String JsFormulaStr ) { double solutionValue = 0; ScriptEngineManager mgr =
public double myEval(String JsFormulaStr ) {
double solutionValue = 0;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine eng = mgr.getEngineByName("JavaScript");
if(eng == null) { // Added this block of code to prevent java.lang.NullPointerException...
log.severe("Unable to get Script Engine." );
return 0;
}
try {
Object jsResults = eng.eval(JsFormulaStr);
solutionValue = Double.parseDouble(jsResults.toString());
return solutionValue;
} catch(Exception e) {
log.severe("[ERROR] in getCalculatedSolution_FromJS_ToDouble()::\n\t" +
"Formula String is: " + JsFormulaStr + "\n\t" + e);
return 0;
}
}
如果我在本地以WebApp的形式运行它(在Eclipse和Netbeans中,以及在Tomcat和glassfish4.0中),一切都可以正常工作
我尝试求值的一些字符串:
- 62.0/100
- 0.0*352.0
- (0-428)*1000
- (0-597)*1000
- 73.0/100
兰迪我遇到了同样的问题。尽管这些类被列入了白名单,但它们的功能似乎在AppEngine上受到了限制。该代码在本地计算机上运行良好,但部署到App Engine时失败,因为没有任何可用的脚本引擎(因此出现NullPointerException) 幸运的是,你可以用Rhino引擎做同样的事情 注意:此示例建立在Harsha R在 下载并将js.jar添加到类路径中(如果您使用的是Java1.4,则只需要js-14.jar)
/*示例1:运行JavaScript函数(取自示例)*/
String script=“函数abc(x,y){返回x+y;}”;
Context=Context.enter();
试一试{
ScriptableObject范围=context.initStandardObjects();
Scriptable that=context.newObject(范围);
函数fct=context.compileFunction(作用域,脚本,“脚本”,1,null);
objectresult=fct.call(context、scope、that、newobject[]{2,3});
System.out.println(Context.jsToJava(result,int.class));
}
最后{
Context.exit();
}
/*示例2:执行JavaScript语句*/
script=“3+2*(4*5)”;
context=context.enter();
试一试{
Scriptable scope=context.initStandardObjects();
Object result=context.evaluateString(作用域,脚本,“”,1,null);
系统输出打印项次(结果);
}
最后{
Context.exit();
}
/* Example 1: Running a JavaScript function (taken from examples) */
String script = "function abc(x,y) {return x+y;}";
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();
}
/* Example 2: execute a JavaScript statement */
script = "3 + 2 * (4*5)";
context = Context.enter();
try{
Scriptable scope = context.initStandardObjects();
Object result = context.evaluateString(scope, script, "<cmd>", 1, null);
System.out.println(result);
}
finally{
Context.exit();
}