Monday, May 12, 2014

Embedding Tomcat8: Minimal

Required dependencies:
  • tomcat-embed-core.jar
  • tomcat-embed-logging-juli.jar
  • servlet-api.jar
  • log4j-1.2.7.jar
  • commons-beanutils-1.8.0.jar
  • commons-codec-1.9.jar
  • commons-collections-3.2.1.jar
  • commons-digester-2.1.jar
  • commons-io-2.4.jar
  • commons-lang-2.6.jar


Sample minimal code to embed and programmatically configure Tomcat 8:

package org.jr.server;

import java.io.File;

import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

public enum Tomcat8Server {
    INSTANCE;
   
    public void startServer(String contextPath, int port) {
        try {
            String docBase = ".";
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(port);
            StandardContext ctx = (StandardContext)tomcat.addContext(contextPath, new File(docBase).getAbsolutePath());
            Tomcat.addServlet(ctx, "mainServlet", new MainServlet());
            ctx.addServletMapping("/*", "mainServlet");
            tomcat.start();
            tomcat.getServer().await();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
        INSTANCE.startServer("", 8090);
    }
}

No comments:

Post a Comment