后端JAVA开发有些代码逻辑其实在JS中很好实现,因为JS的对象定义不是很严格,避免了繁琐的POJO对象创建,JAVA标准库也提供了JS的调用引擎,方便我们直接复用JS的逻辑实现
注意定义JS方法接口中的方法名要与JS中的大小写完全一致,JS中的alert、console无法调用,但可以从异常捕获中获取调用异常的具体信息
代码参考:
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("Nashorn");
String path = GridReportBean.class.getClassLoader().getResource("").getPath();
path = path.replaceAll("%20", " ");
engine.eval(new FileReader(path + "static/asserts/cloudPrint.js"));
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
ICloudPrint executeMethod = invocable.getInterface(ICloudPrint.class);
cloudPrintData = executeMethod.dataWrapper(JSON.toJSONString(printData.get("Detail"))
, cloudPrintPlatform, printerName);
}
public interface ICloudPrint {
String dataWrapper(String dataArrayStr, String cloudPrintPlatform, String printer);
}
版权声明:本文为bldstc2011原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。