• all codes : https://github.com/gaeco/tomcatEmbedded

  • gradle.build

dependencies {
    def tomcatVersion = '8.0.21'

    compile "org.apache.tomcat:tomcat-catalina:${tomcatVersion}"
    compile "org.apache.tomcat:tomcat-coyote:${tomcatVersion}"
    compile "org.apache.tomcat:tomcat-jasper:${tomcatVersion}"

    testCompile group: 'junit', name: 'junit', version: '4.11'
}
  • TomcatServer.java
    private void init(){
        tomcat = new Tomcat();
        tomcat.setPort(port);
        if(contextPath == null){
            contextPath = "";
        }
        if(docBase == null){
            File base = new File(System.getProperty("java.io.tmpdir"));
            docBase = base.getAbsolutePath();
        }
        rootContext = tomcat.addContext(contextPath, docBase);
    }

    public void addServlet(String servletName, String uri, HttpServlet servlet){
        Tomcat.addServlet(this.rootContext, servletName, servlet);
        rootContext.addServletMapping(uri, servletName);
    }

    public void startServer() throws LifecycleException {
        tomcat.start();
        tomcat.getServer().await();
    }