嵌入式Tomcat示例

最近在看李号双老师的《深入拆解Tomcat&Jetty》专栏,思路超清楚,看到源码就怕怕的我也可以看的很欢脱,想看源码一起揭秘呢……
and 老师建议的第一步就是搞个嵌入式的tomcat玩起来,然后断点调试,还贴心地甩了个demo。我天……晕了晕了,找了个适合我这种小渣渣看的示例,超清楚!转发!!!

李号双老师推荐的示例:https://github.com/heroku/devcenter-embedded-tomcat
我找的这位大佬的文章:Java Web 学习笔记之十六:嵌入式web服务器Tomcat的基本使用
对着李号双老师讲的Tomcat框架来看,这份代码非常好上手,也很好理解。推荐直接跳转看哦,排版也是美的美的,俺只是个实名搬运工。


1、简介

嵌入式Tomcat服务器则无需部署外置tomcat,开发者只需引入嵌入式tomcat依赖,编写少量启动代码即可运行Web应用,是搭建微服务应用的首选方式之一。

2、Maven配置

建一个简单的maven工程就可以啦,不必是Java web哦。pom.xml文件的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ellie</groupId>
    <artifactId>tomcat</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <tomcat.version>9.0.19</tomcat.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper-el</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>TomcatSample</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

build部分是可选的,主要是因为用的开发工具是IntelliJ IDEA,默认Java5,所以每次都会粘个方便的build过来。

3、简简单单的tomcat启动

简单的意思就是tomcat可以启起来,然后啥也没得(后面有介绍添加servlet的方法的啦~)

public class MyTomcat {
    public static void main(String[] args) throws Exception {

        // 创建临时目录作为tomcat的基础目录
        Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");
        // 创建临时目录作为应用文档资源的目录
        Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");

        Tomcat tomcat = new Tomcat();
        Connector connector = new Connector();
        // 设置绑定端口
        connector.setPort(8080);
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());

        // 创建应用上下文
        String contextPath = "/ellie";
        StandardContext context = (StandardContext) tomcat.addWebapp(
                contextPath, tempDocDir.toFile().getAbsolutePath());
        context.setParentClassLoader(MyTomcat.class.getClassLoader());
        context.setUseRelativeRedirects(false);

        // TODO:添加servlet

        //tomcat 启动jar扫描设置为跳过所有,避免与框架结合出现 jar file not found exception
        System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "\\,*");

        tomcat.start();
        tomcat.getServer().await();
    }
}

附上李号双老师讲课给的Tomcat框架图:

4、添加servlet

添加Servelt有三种方式:

  • 通过 org.apache.catalina.startup.Tomcat#addServlet 方法添加。
  • 通过 org.apache.catalina.Wrapper 对象进行配置,并添加到上下文中。
  • 实现Servlet类的时候使用注解 javax.servlet.annotation.WebServlet 进行修饰,通过应用启动后的Tomcat容器自动扫描添加。

三种使用方式的代码如下:

		// addServlet方法添加
		{
            tomcat.addServlet(contextPath, "test1Name", TestServlet.class.getName());
            //注意不要忘记设置Servlet路径映射
            context.addServletMappingDecoded("/test1Path/*", "test1Name");
        }
        
        // Wrapper对象进行配置
        {
            Wrapper wrapper = context.createWrapper();
            wrapper.setName("test2Name");
            wrapper.setServletClass(TestServlet2.class.getName());
            context.addChild(wrapper);
            context.addServletMappingDecoded("/test2Path/*", "test2Name");
        }

这两种方法对应的Servlet写法如下:

public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().println("Hello, world! -1-");
    }
}

第三种方式添加servlet是直接在Servlet上使用注解,示例如下:

@WebServlet(name = "test3", urlPatterns = {"/test3/*"})
public class TestServlet3 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().println("Hello, world! -3-");
    }
}

使用这种方式需要保证配置的资源集 中包含有该类型的(class资源集合或lib资源集合),也就是要告诉Tomcat怎么找到它。

5、配置应用资源集合

代码如下:

	private static void configureResources(StandardContext context) {
        String WORK_HOME = System.getProperty("user.dir");
        File classesDir = new File(WORK_HOME, "target/classes");
        File jarDir = new File(WORK_HOME, "lib");
        WebResourceRoot resources = new StandardRoot(context);
        if (classesDir.exists()) {
            resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", classesDir.getAbsolutePath(), "/"));
            System.out.println("Resources added: [classes]");
        } else if (jarDir.exists()) {
            resources.addJarResources(new DirResourceSet(resources, "/WEB-INF/lib", jarDir.getAbsolutePath(), "/"));
            System.out.println("Resources added: [jar]");
        } else {
            resources.addPreResources(new EmptyResourceSet(resources));
            System.out.println("Resources added: [empty]");
        }
        context.setResources(resources);
    }

代码说明:

  • WORK_HOME就是程序的工作目录
  • 若存在target/classes目录则认为程序在IDE环境中启动,讲classes目录下的资源作为PreResources添加至上下文中
  • 若存在lib目录,则认为程序是在构建打包后,通过脚本启动的,则将lib目录下的资源作为JarResources添加至上下文中,可根据实际目录进行配置,不一定是lib目录。
  • 应用资源集合不是必须配置项。如果没有配置,在程序中使用注解定义的Servlet类型就无法通过Tomcat自动加载。(比如我,一开始就一脸懵逼不知道Servlet为啥像消失了一样)

6、完整demo

最后成型的代码如下:

public class MyTomcat {
    public static void main(String[] args) throws Exception {
        // 创建临时目录作为tomcat的基础目录
        Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");
        // 创建临时目录作为应用文档资源的目录
        Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");

        Tomcat tomcat = new Tomcat();
        Connector connector = new Connector();
        // 设置绑定端口
        connector.setPort(8080);
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());

        // 创建应用上下文
        String contextPath = "/ellie";
        StandardContext context = (StandardContext) tomcat.addWebapp(
                contextPath, tempDocDir.toFile().getAbsolutePath());
        context.setParentClassLoader(MyTomcat.class.getClassLoader());
        context.setUseRelativeRedirects(false);

        // 添加servlet
        configureServlets(contextPath, tomcat, context);
        configureResources(context);

        //tomcat 启动jar扫描设置为跳过所有,避免与框架结合出现 jar file not found exception
        System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "\\,*");

        tomcat.start();
        tomcat.getServer().await();
    }

    private static void configureResources(StandardContext context) {
        String WORK_HOME = System.getProperty("user.dir");
        File classesDir = new File(WORK_HOME, "target/classes");
        File jarDir = new File(WORK_HOME, "lib");
        WebResourceRoot resources = new StandardRoot(context);
        if (classesDir.exists()) {
            resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", classesDir.getAbsolutePath(), "/"));
            System.out.println("Resources added: [classes]");
        } else if (jarDir.exists()) {
            resources.addJarResources(new DirResourceSet(resources, "/WEB-INF/lib", jarDir.getAbsolutePath(), "/"));
            System.out.println("Resources added: [jar]");
        } else {
            resources.addPreResources(new EmptyResourceSet(resources));
            System.out.println("Resources added: [empty]");
        }
        context.setResources(resources);
    }

    private static void configureServlets(String contextPath, Tomcat tomcat, StandardContext context) {
        {
            tomcat.addServlet(contextPath, "test1Name", TestServlet.class.getName());
            //注意不要忘记设置Servlet路径映射
            context.addServletMappingDecoded("/test1Path/*", "test1Name");
        }
        {
            Wrapper wrapper = context.createWrapper();
            wrapper.setName("test2Name");
            wrapper.setServletClass(TestServlet2.class.getName());
            context.addChild(wrapper);
            context.addServletMappingDecoded("/test2Path/*", "test2Name");
        }
    }
}

通过浏览器访问:

其中的ellie是俺设置的contextPath啦。然后访问的时候就发现会生成临时目录:

7、初始参数、Filters和Listeners

这三个部分暂时没有用到,不过大佬封装一下,看着很干净,列出来啦:

	private static void configureContextParameters(StandardContext context) {
        context.addParameter("param1", "1");
        context.addParameter("param2", "2");
    }
    
    private static void configureFilters(StandardContext context) {
        //Filter定义
        FilterDef filterDef = new FilterDef();
        filterDef.setFilterName("test-filter");
        filterDef.setFilterClass(TestFilter.class.getName());
        filterDef.addInitParameter("name", "test-filter");
        context.addFilterDef(filterDef);
        //Filter路径映射
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName("test-filter");
        filterMap.addURLPattern("/*");
        context.addFilterMap(filterMap);
    }

    private static void configureListeners(StandardContext context) {
        context.addApplicationEventListener(new TestListener());
    }

用到的Filter:

public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Enumeration<String> enumeration = filterConfig.getInitParameterNames();
        if (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            System.out.println(String.format("Filter init: init-param name:[%s], value:[%s]", name, filterConfig.getInitParameter(name)));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println(String.format("Filter doFilter: remote host: [%s]", request.getRemoteHost()));
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

用到的Listener:

public class TestListener implements LifecycleListener {

    @Override
    public void lifecycleEvent(LifecycleEvent event) {

        if (event != null && event.getLifecycle() != null) {
            System.out.println(event.getLifecycle().getStateName() + "ellie");
        }

        if (!(event.getLifecycle() instanceof Server)) {
            return;
        }

        if (!Lifecycle.AFTER_START_EVENT.equals(event.getType())) {
            return;
        }

        Server server = (Server) event.getLifecycle();
    }
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值