我有一个嵌入 Tomcat 的 Java Swing 应用程序。嵌入式 Tomcat 以编程方式配置;没有 xml。Tomcat 也使用 Groovy Servlets 进行配置:
StandardWrapper gspWrapper = new StandardWrapper();
gspWrapper.setName("groovy");
gspWrapper.setServletName("groovy");
gspWrapper.setServletClass(GroovyServlet.class.getName());
gspWrapper.addInitParameter("fork", "false");
gspWrapper.setLoadOnStartup(2);
我也想要 Ruby 支持(jRuby 1.7)。所以我想以与 Groovy 支持相同的方式配置它:
StandardWrapper rubyWrapper = new StandardWrapper();
rubyWrapper.setName("rb");
rubyWrapper.setServletName("rb");
rubyWrapper.setServletClass(JRubyServlet.class.getName());
rubyWrapper.addInitParameter("fork", "false");
rubyWrapper.setLoadOnStartup(2);
我尝试编写 JRubyServlet 类,但我不知道如何执行脚本并将输出写入响应。这是我当前的代码:
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);
}
}