首页   快速返回

tomcat8.5嵌入式启动     所属分类 tomcat
先建一个标准的 maven web 项目


tomcat.embed.version 8.5.0

引入依赖




<dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.embed.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>${tomcat.embed.version}</version>
            <!--<scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-logging-juli</artifactId>
            <version>${tomcat.embed.version}</version>
        </dependency>
        
 
<dependency>
    <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
</dependency>

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8</version>
        </dependency>
 



先放一个最简单jsp页面 , 也可以使用 servlet
src/main/webapp/index.jsp

写一个java类用于启动 tomcat 

dyyx/TomcatServerStart.java


package dyyx; import java.net.URL; import java.util.Date; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang3.StringUtils; public class TomcatServerStart { private static int port = 8080; // / // A context path must either be an empty string or start with a '/' and do not end with a '/' private static String contextPath = ""; public static void main(final String[] args) throws Exception{ System.out.println("TomcatServerStart,"+new Date()); start(); } public static void start() throws Exception { Tomcat tomcat = new Tomcat(); String resource = "dyyx/TomcatServerStart.class"; URL url = TomcatServerStart.class.getClassLoader().getResource(resource); System.out.println(url); String path = url.getPath(); System.out.println(path); String classesPath = "target/classes/"; String base = StringUtils.substringBefore(path, classesPath); // String baseDir = "/Users/dugang/fun/hellocode/project/tomcat-embed/target/classes/"; // String webAppDir = "/Users/dugang/fun/hellocode/project/tomcat-embed/src/main/webapp/"; String webAppDir = base + "src/main/webapp/"; String baseDir = base + classesPath; System.out.println("baseDir="+baseDir); System.out.println("webAppDir="+webAppDir); tomcat.setBaseDir(baseDir); tomcat.setPort(port); tomcat.addWebapp(contextPath, webAppDir); // tomcat.enableNaming(); tomcat.start(); tomcat.getServer().await(); } } 使用嵌入式启动,可以愉快的跟踪调试, 譬如 tomcat 的 启动过程

上一篇     下一篇
maven命令行运行main方法

tomcat8.5压测记录

tomcat8.5类加载机制

tomcat8.5架构概述

tomcat8.5启动过程远程调试

tomcat8.5 jsp编译过程