0

So I have a little API I've developed that I'd like to zip up in a JAR file, but I want to embed Tomcat so that if someone has the code they can just run it instead of having to configure their own server. I'm using the java eclipse ide, does anyone know how I could embed it. I keep reading about eclipse having an embedded tomcat server or something but I don't know if that's what I want. Feel free to link me to a tutorial or anything, I failed at googling. EDIT: This is a webapp.

1 Answers1

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>");
        }
    }
}
anotherdave
  • 6,656
  • 4
  • 34
  • 65