Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Embedded Tomcat 7
package bootstrap;
public final class Bootstrap {
public static void main(String[] args) {
new TomcatServer("../project/module").boot(8080);
}
private Bootstrap() {}
}
package bootstrap;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.HostConfig;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import java.nio.file.Path;
import java.nio.file.Paths;
class TomcatServer {
private static final Logger LOGGER = LoggerFactory.getLogger(TomcatServer.class);
private final String baseDir;
private final String webAppDir;
TomcatServer(String baseDir) {
this(baseDir, "/src/main/webapp");
}
TomcatServer(String baseDir, String webAppDir) {
this.baseDir = baseDir;
this.webAppDir = webAppDir;
}
void boot(int port) {
try {
Tomcat tomcat = createServer(port);
tomcat.start();
tomcat.getServer().await();
LOGGER.info("Server started on {}", port);
} catch (ServletException | LifecycleException e) {
LOGGER.error("Failed to boot server", e);
System.exit(-1);
}
}
private Tomcat createServer(int port) throws ServletException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(port);
Host host = tomcat.getHost();
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.addLifecycleListener(new HostConfig());
Path webAppPath = Paths.get(baseDir, webAppDir);
Path webXmlPath = webAppPath.resolve("WEB-INF/web.xml");
Context context = tomcat.addWebapp("/", webAppPath.toFile().getAbsolutePath());
context.setAltDDName(webXmlPath.toFile().getAbsolutePath());
return tomcat;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.