SpringBoot内嵌tomcat原理

SpringBoot内嵌Tomcat实现

SpringBoot通过spring-boot-starter-web依赖来内嵌Tomcat,通过Tomcat提供的外部接口类org.apache.catalina.startup.Tomcat来实现。
spring-boot-starter-web依赖包含了spring-boot-starter-tomcat依赖。

点击run之后,右上角选择Download source下载源码。

手写内嵌Tomcat

pom.xml中引入Tomcat依赖

<dependencies>
    <dependency>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
    </dependency>
</dependencies>

作为嵌入Tomcat入口的EmbeddedTomcatServer类

import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

public class EmbeddedTomcatServer {
    public static void main(String[] args) throws Exception {
        // 获取用户当前工作目录即获取当前项目根目录的绝对路径
        String classpath = System.getProperty("user.dir");
        System.out.println(classpath);

        Tomcat tomcat = new Tomcat();
        //加载工程class
        tomcat.addContext(tomcat.getHost(), "/", classpath);
        //设置Servlet
        Wrapper wrapper = tomcat.addServlet("/", "HelloServlet", new HelloServlet());
        wrapper.addMapping("/hello");

        tomcat.start();
        // 强制TomcatServer等待,避免main线程执行结束后关闭
        tomcat.getServer().await();
    }
}

处理Web请求的HelloServlet类

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        out.println("hello servlet");
    }
}

结果

参考资料

SpringBoot内嵌Tomcat原理剖析

 

posted on 2023-03-13 16:28  王景迁  阅读(155)  评论(0编辑  收藏  举报

导航