美文网首页
tomcat源码分析(1) Embed Tomcat快速搭建

tomcat源码分析(1) Embed Tomcat快速搭建

作者: 全都是泡沫啦 | 来源:发表于2018-08-29 15:44 被阅读0次

tomcat是我们常用web服务器,这里我们使用嵌入式tomcat进行讲解,后续使用tomcat源码进行分析(如果想直接源码进行分析的小伙伴可以直接pull代码https://github.com/paulzhangcc/tomcat-8.0.53.git

1.从https://start.spring.io/快速创建项目,我选用的配置Generate a Maven Project with Java and Spring Boot 1.5.15 其中Dependencies选择Web,填写Group Artifact 后生成代码导入IDEA (版本1.5.15 依赖的embed tomcat 是8.5.32)

2.创建类EmbedTomcatHttp

public class EmbedTomcatHttp {
    public static void main(String[] args) throws Exception {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080);
        tomcat.setBaseDir("/tmp/tomcat");
        String contextPath = "";
        StandardContext context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());
        tomcat.getHost().addChild(context);

        tomcat.addServlet(contextPath, "apiServlet", new GenericServlet() {
            @Override
            public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
                HttpServletRequest request;
                HttpServletResponse response;
                try {
                    request = (HttpServletRequest) servletRequest;
                    response = (HttpServletResponse) servletResponse;
                } catch (ClassCastException var6) {
                    throw new ServletException("non-HTTP request or response");
                }
                response.setStatus(200);
                response.getWriter().append("Hello World...");
            }
        });
        context.addServletMappingDecoded("/api", "apiServlet");
        //tomcat.addWebapp("/tomcat", "/root/apache-tomcat-8.0.53/webapps/ROOT");
        //设置不开启keep-alive
        //AbstractHttp11Protocol abstractHttp11Protocol = (AbstractHttp11Protocol)(tomcat.getConnector().getProtocolHandler());
        //abstractHttp11Protocol.setMaxKeepAliveRequests(1);
        tomcat.start();
        tomcat.getServer().await();
    }
}

3.运行EmbedTomcatHttp的main方法,浏览器输入http://127.0.0.1:8080/api 页面返回结果Hello World...

4.对于使用webapps进行jsp应用的访问还需要一下的配置

tomcat.addWebapp("/tomcat", "/root/apache-tomcat-8.0.53/webapps/ROOT");

依赖的jar包

<dependency>
    <groupId>org.eclipse.jdt.core.compiler</groupId>
    <artifactId>ecj</artifactId>
    <version>4.5.1</version>
</dependency>

下面这些包需要从tomcat lib 目录进行拷贝


嵌入式tomcat中jsp依赖的jar.png

注:读者可以不使用spring boot 只要将embed tomcat的依赖包引入到项目中即可,后续我们会开始分析tomcat

相关文章

网友评论

      本文标题:tomcat源码分析(1) Embed Tomcat快速搭建

      本文链接:https://www.haomeiwen.com/subject/hbxkwftx.html