Pure JS (6.1):使用 Rhino Shell 和 Debugger 运行和调试 JS
之前一直使用 java 7 自带的 ScriptEngine 执行服务器端 JS,然而,一个重要的缺陷是无法进行调试。
因此我将之前的一些 Java 代码改为 JavaScript 代码,并尝试着使用 Rhino Debugger。
本文就是介绍这方面的探索成果的。
1. Rhino Shell 和 Debugger 介绍
Rhino Shell 可以用于执行 JS,与之前直接通过 Run As Java Application 方式运行没有太大区别。
Rhino Debugger 是一个可以用于调试的 GUI 工具。
为了使用 Rhino Shell 和 Debugger ,首先需要下载 js.jar ,并将其添加到 Build Path 中。
js.jar 的下载地址:http://www.mozilla.org/rhino/download.html
Rhino 官网关于 Shell 和 Debugger 的介绍:
http://www.mozilla.org/rhino/shell.html
http://www.mozilla.org/rhino/debugger.html
2. Java 代码转为 JavaScript 代码
为了更方便地使用 Rhino Debugger 进行调试,我将之前的一些 Java 代码转换成了 JavaScript 代码。
以下是 script/server.js 的内容,用于代替之前的 JSServer 类(http://xxing22657-yahoo-com-cn.iteye.com/blog/1052485):
(function() { var imp, dirs, defaults, server, context; try { importer(); consts(); loadScripts(); startMonit(); startServer(); } catch (e) { print(e); } function importer() { imp = JavaImporter( java.io, org.eclipse.jetty.server, org.eclipse.jetty.servlet, com.purejs.lib); } function consts() { dirs = ["scripts/lib", "webapp/js/both", "scripts/app"]; defaults = "*.js,*.css,*.ico,*.txt,*.png,*.jpg,*.gif,*.htm,*.html,*.swf"; } function loadScripts() { print("Loading Scripts ..."); load("scripts/config.js"); loadDirs(dirs); } function startMonit() { print("Starting Monit ..."); pure.each = each; pure.monit(dirs, function(file){ file = imp.File(file); if(file.exists() && file.file) { load(file); } }); } function startServer() { print("Starting Server ..."); createServer(); server.start(); server.join(); } // 以下省略... }());
scripts/lib/pure/apiServlet.js 的内容如下,用于代替之前的 JSServlet:
(function() { var servlet = javax.servlet.http.HttpServlet; pure.apiServlet = servlet({ service: service }); function service(req, res) { var result; try { result = run(req, res); } catch (e) { print(e); result = { error: e.toString(), success: false } } if (result != null) { res.setContentType("text/html; charset=UTF8"); res.getWriter().write(JSON.stringify(result)); } } function run(req, res) { // 省略 ... } }());
其他几个类也进行了替换,请下载附件并查看。
3. Run Configurations 设置,运行与调试效果
将 js.jar 添加到项目中之后,我们还需要在 Run Configurations 窗口中设置:
如图,首先需要选择 菜单中的 Run Configurations ...,并创建新的 Configuration:


我们需要分别为 shell 和 debugger 进行设置。
Rhino Shell 的设置如下:


Rhio Debugger 的设置如下:


第一次运行时需要点击窗口右下角的“Run”按钮,之后就可以在快捷菜单中选择 PureJS 和 PureJS_debug 进行启动了:

以下是调试的效果:



当然,仅仅有 debugger 还是不够的,我们还需要测试、日志、编译等等。
以下是近期的研究列表:
使用 Rhino Unit 进行测试 (http://xxing22657-yahoo-com-cn.iteye.com/blog/1131612)
日志和 proxy 对象 (http://xxing22657-yahoo-com-cn.iteye.com/blog/1136195)
权限控制、数据验证 (http://xxing22657-yahoo-com-cn.iteye.com/blog/1136987)
增强可配置性 (http://xxing22657-yahoo-com-cn.iteye.com/blog/1137790)
配置 Spket 智能感知
使用 Rhino Compliler 编译项目
完成这些研究之后,我们就有一个基本的 Server-side JS 框架了。