Created
December 30, 2014 04:28
-
-
Save monzou/4f9d8a296528254bcbb2 to your computer and use it in GitHub Desktop.
Embedded Tomcat 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package bootstrap; | |
public final class Bootstrap { | |
public static void main(String[] args) { | |
new TomcatServer("../project/module").boot(8080); | |
} | |
private Bootstrap() {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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