E4Xでサーブレット

E4Xをサーブレットで使えたら面白いんじゃなかろうかと思って実装。
こんな感じのフレームワークってないのかなぁ?Rhino速いんだし…


servlet.jsがこんな感じで、http://localhost:8080//rhino-servlet/servlet.jsにアクセス。


var body =
<html>
<body>
hello, Rhino!
</body>
</html>
;

out.println(body);

RhinoServletがこんな感じ。


public class RhinoServlet extends HttpServlet {

protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletContext app = getServletContext();
ServletConfig conf = getServletConfig();
String filename = req.getPathInfo();
InputStream in = app.getResourceAsStream("/js/" + filename);
InputStreamReader reader = new InputStreamReader(in);

try {
runScript(reader, filename, app, conf, req, res);
} finally {
reader.close();
in.close();
}
}

private void runScript(Reader in, String filename, ServletContext app,
ServletConfig conf, HttpServletRequest req, HttpServletResponse res)
throws IOException {
Context cx = Context.enter();

try {
Script script = cx.compileReader(in, filename, 1, null);
Global global = new Global();
ShellContextFactory factory = new ShellContextFactory();
global.init(factory);

putProperty(app, "application", global);
putProperty(conf, "config", global);
putProperty(res.getWriter(), "out", global);
putProperty(req, "request", global);
putProperty(res, "response", global);
putProperty(req.getSession(), "session", global);

Object result = script.exec(cx, global);

if (result != Context.getUndefinedValue())
System.err.println(Context.toString(result));
} finally {
Context.exit();
}
}

private void putProperty(Object obj, String name, Scriptable scope) {
Object jsObj = Context.javaToJS(obj, scope);
ScriptableObject.putProperty(scope, name, jsObj);
}

}