0

所以我有一个我开发的小 API,我想压缩到一个 JAR 文件中,但我想嵌入 Tomcat,这样如果有人有代码,他们就可以运行它,而不必配置自己的服务器。我正在使用java eclipse ide,有谁知道我如何嵌入它。我一直在阅读有关 eclipse 具有嵌入式 tomcat 服务器或其他东西的信息,但我不知道这是否是我想要的。随意将我链接到教程或任何东西,我在谷歌上搜索失败。编辑:这是一个网络应用程序。

4

1 回答 1

2

While not exacting what you're asking for (Tomcat), I'd recommend including Jetty as a light-weight alternative. You can include it within your JAR as a Maven dependency & it's straight-forward to get a server up & running from your code.

From their example on their website, a server with a basic servlet could be done as easily as:

public class MinimalServlets {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);
        handler.addServletWithMapping(HelloServlet.class, "/*");
        server.start();
        server.join();
    }

    public static class HelloServlet extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>Hello SimpleServlet</h1>");
        }
    }
}
于 2013-07-15T18:56:30.153 回答