I have a Java Swing application that embeds Tomcat. The embedded Tomcat is configured programmatically; no xml. Tomcat is also configured using Groovy Servlets:
StandardWrapper gspWrapper = new StandardWrapper();
gspWrapper.setName("groovy");
gspWrapper.setServletName("groovy");
gspWrapper.setServletClass(GroovyServlet.class.getName());
gspWrapper.addInitParameter("fork", "false");
gspWrapper.setLoadOnStartup(2);
I want Ruby support (jRuby 1.7), too. So I want to configure it same same way as the Groovy support:
StandardWrapper rubyWrapper = new StandardWrapper();
rubyWrapper.setName("rb");
rubyWrapper.setServletName("rb");
rubyWrapper.setServletClass(JRubyServlet.class.getName());
rubyWrapper.addInitParameter("fork", "false");
rubyWrapper.setLoadOnStartup(2);
I tried to write the JRubyServlet class, but I don’t know how to execute a script an write the output into the response. Here’s my current code:
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jruby.Ruby;
import org.jruby.javasupport.JavaEmbedUtils;
public class JRubyServlet extends HttpServlet {
private static final long serialVersionUID = -6913887886084787803L;
private Ruby ruby;
@Override public void init(ServletConfig config) throws ServletException {
super.init(config);
ruby = JavaEmbedUtils.initialize(new ArrayList<String> ());
}
@Override public void destroy() {
JavaEmbedUtils.terminate(ruby);
super.destroy();
}
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//How do you execute the script here?
}
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doGet(req, res);
}
}
Here is a way of doing this using
JavaEmbedUtilsas per your example.You can first create a servlet written in JRuby (here in
src/main/ruby/ruby_servlet.rb), for instance:You can then use your
JRubyServletto call this JRuby script:Have a look also at https://github.com/jruby/jruby/wiki/RedBridge; using JRuby Embed provides ways of controlling concurrency model, etc.