JRuby + Jetty

I finally figured out how to get JRuby to serve a Jetty servlet today (thanks to Charles). The key was flipping what I’d been trying to do for a while (getting Jetty to run JRuby). Here’s code that implements the AbstractHandler interface pretty trivially:

$ cat jetty_example.jrb
require 'java'
include_class 'javax.servlet.ServletException'
include_class 'javax.servlet.http.HttpServlet'
include_class 'javax.servlet.http.HttpServletRequest'
include_class 'javax.servlet.http.HttpServletResponse'

include_class 'org.mortbay.jetty.Server'
include_class 'org.mortbay.jetty.servlet.Context'
include_class 'org.mortbay.jetty.servlet.ServletHolder'
include_class 'org.mortbay.jetty.handler.AbstractHandler'

class SimpleHandler < AbstractHandler
  def handle(target, request, response, dispatch)
    response.setContentType("text/html")
    response.setStatus(HttpServletResponse::SC_OK)
    response.getWriter().println("<h1>Goodbye, cruel monoglot world!</h1>")
    request.setHandled(true)
  end
end

handler = SimpleHandler.new
server = Server.new(8080)
server.setHandler(handler)
server.start()

To run, add Jetty to your classpath:

$ export CLASSPATH="/path/to/jetty-6.1.3.jar:/.../jetty-util-6.1.3.jar:/.../servlet-api-2.5-6.1.3.jar"

Then it’s just a normal JRuby invocation:

$ jruby jetty_example.jrb

It’s trivial code at this point (and doesn’t handle concurrent requests, maxing out at 6.47r/s across my network), but at least it’s got me started.

[UPDATE: I can get the non-concurrent request handling way down with just a few simple tweaks (mainly running JRuby in SERVER mode) and running ab locally ;-)]

Comments are closed.