Pure JS (6.1):使用 Rhino Shell 和 Debugger 运行和调试 JS
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();}// 以下省略...}());
(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) {// 省略 ...}}());