jfinal 内嵌tomcat,打包可运行jar

[TOC]
当需要快速开发并部署web项目时,传统的方式需要在服务器上部署tomcat并配置端口等等配置,比较麻烦及低效率。而直接部署可运行jar的方式提供web服务效率会有比较大的提升。

项目结构

TomcatConfig.java

package com.eblly.tomcat;

import com.jfinal.config.*;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.template.Engine;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

/**
 * @author eblly
 * @since 2019/4/1
 */
public class TomcatConfig extends JFinalConfig {

    static Prop prop = PropKit.use("config.properties");

    @Override
    public void configConstant(Constants constants) {

    }

    @Override
    public void configRoute(Routes routes) {
        routes.add("/helloworld", HelloworldController.class);
    }

    @Override
    public void configEngine(Engine engine) {

    }

    @Override
    public void configPlugin(Plugins plugins) {

    }

    @Override
    public void configInterceptor(Interceptors interceptors) {

    }

    @Override
    public void configHandler(Handlers handlers) {

    }

    public static void main(String[] args) throws LifecycleException {

        int port = 8888;
        String contextPath = "/";

        // 项目中web目录名称,以前版本为WebRoot、webapp、webapps,现在为WebContent
        String baseDir = new File("webapp/").getAbsolutePath();
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setBaseDir(".");

        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        server.addLifecycleListener(listener);
        tomcat.addWebapp(contextPath, baseDir);

        tomcat.start();

        tomcat.getServer().await();
    }
}
<?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">
    <parent>
        <artifactId>jfinalCase</artifactId>
        <groupId>com.eblly</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>tomcatEmbed</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <!-- tomcat-embed-core -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>8.5.39</version>
        </dependency>

        <!-- tomcat-embed-el -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-el</artifactId>
            <version>8.5.39</version>
        </dependency>

        <!-- tomcat-embed-jasper -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>8.5.39</version>
        </dependency>

        <!-- javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <!--<scope>provided</scope>-->
        </dependency>

    </dependencies>


    <!-- 分环境打包配置文件 -->
    <profiles>
        <!-- 本地环境 -->
        <profile>
            <id>local</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/local</directory>
                    </resource>
                </resources>
            </build>

            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <env.profile>local</env.profile>
            </properties>
        </profile>

        <!-- 开发环境 -->
        <profile>
            <id>dev</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/dev</directory>
                    </resource>
                </resources>
            </build>

            <properties>
                <env.profile>dev</env.profile>
            </properties>
        </profile>

        <!--测试环境-->
        <profile>
            <id>tests</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/tests</directory>
                    </resource>
                </resources>
            </build>
            <properties>
                <env.profile>tests</env.profile>
            </properties>
        </profile>

        <!--线上环境-->
        <profile>
            <id>prod</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/prod</directory>
                    </resource>
                </resources>
            </build>

            <properties>
                <env.profile>prod</env.profile>
            </properties>
        </profile>

    </profiles>

    <build>
        <finalName>tomcatEmbed</finalName>

        <!--  -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>local/**</exclude>
                    <exclude>dev/**</exclude>
                    <exclude>tests/**</exclude>
                    <exclude>prod/**</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>

        </resources>

        <plugins>
            <!-- 编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!--
                jar 包中的配置文件优先级高于 config 目录下的 "同名文件"
                因此,打包时需要排除掉 jar 包中来自 src/main/resources 目录的
                配置文件,否则部署时 config 目录中的同名配置文件不会生效
             -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <excludes>
                        <exclude>/*.*</exclude>
                    </excludes>
                </configuration>
            </plugin>

            <!--
                使用 mvn clean package 打包
                更多配置可参考官司方文档:http://maven.apache.org/plugins/maven-assembly-plugin/single-mojo.html
            -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>

                        <configuration>
                            <!-- 打包生成的文件名 -->
                            <finalName>${project.build.finalName}</finalName>
                            <!-- jar 等压缩文件在被打包进入 zip、tar.gz 时是否压缩,设置为 false 可加快打包速度 -->
                            <recompressZippedFiles>true</recompressZippedFiles>
                            <!-- 打包生成的文件是否要追加 release.xml 中定义的 id 值 -->
                            <appendAssemblyId>true</appendAssemblyId>
                            <!-- 指向打包描述文件 package.xml -->
                            <descriptors>
                                <descriptor>package.xml</descriptor>
                            </descriptors>
                            <!-- 打包结果输出的基础目录 -->
                            <outputDirectory>${project.build.directory}/</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>

package.xml

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">

    <!--
      assembly 打包配置更多配置可参考官司方文档:
      http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html
    -->

    <id>release-${env.profile}</id>

    <!--
        设置打包格式,可同时设置多种格式,常用格式有:dir、zip、tar、tar.gz
        dir 格式便于在本地测试打包结果
        zip 格式便于 windows 系统下解压运行
        tar、tar.gz 格式便于 linux 系统下解压运行
    -->
    <formats>
        <format>dir</format>
        <!--<format>zip</format>-->
        <format>tar.gz</format>
    </formats>

    <!-- 打 zip 设置为 true 时,会在 zip 包中生成一个根目录,打 dir 时设置为 false 少层目录 -->
    <includeBaseDirectory>true</includeBaseDirectory>

    <fileSets>
        <fileSet>
            <directory>${basedir}/src/main/resources</directory>
            <outputDirectory>config</outputDirectory>

            <excludes>
                <exclude>local/**</exclude>
                <exclude>dev/**</exclude>
                <exclude>tests/**</exclude>
                <exclude>prod/**</exclude>
            </excludes>
        </fileSet>

        <!-- src/main/resources 全部 copy 到 config 目录下 -->
        <fileSet>
            <directory>${basedir}/src/main/resources/${env.profile}</directory>
            <outputDirectory>config</outputDirectory>
        </fileSet>

        <!-- src/main/webapp 全部 copy 到 webapp 目录下 -->
        <fileSet>
            <directory>${basedir}/webapp</directory>
            <outputDirectory>webapp</outputDirectory>
        </fileSet>

        <!-- 项目根下面的脚本文件 copy 到根目录下 -->
        <fileSet>
            <directory>${basedir}</directory>
            <outputDirectory></outputDirectory>
            <!-- 脚本文件在 linux 下的权限设为 755,无需 chmod 可直接运行 -->
            <fileMode>755</fileMode>
            <includes>
                <include>bin/</include>
                <!--<include>*.sh</include>-->
                <!--<include>*.bat</include>-->
            </includes>
        </fileSet>
    </fileSets>

    <!-- 依赖的 jar 包 copy 到 lib 目录下 -->
    <dependencySets>
        <dependencySet>
            <outputDirectory>lib</outputDirectory>
        </dependencySet>
    </dependencySets>

</assembly>

运行命令mvn clean package -Dmaven.test.skip=true -Pdev进行打包。
打包后target结构如下

image.png

进入target中目录,运行命令./bin/start.sh

main_class: com.eblly.tomcat.TomcatConfig
Apr 02, 2019 11:01:33 AM org.apache.catalina.core.StandardContext setPath
警告: A context path must either be an empty string or start with a '/' and do not end with a '/'. The path [/] does not meet these criteria and has been changed to []
Apr 02, 2019 11:01:33 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/eblly/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
Apr 02, 2019 11:01:33 AM org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8888"]
Apr 02, 2019 11:01:33 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
Apr 02, 2019 11:01:33 AM org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
Apr 02, 2019 11:01:33 AM org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.39
Apr 02, 2019 11:01:33 AM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
信息: No global web.xml found
Apr 02, 2019 11:01:33 AM org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Apr 02, 2019 11:01:33 AM org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8888"]

项目启动成功。访问:localhost:8888/helloworld/list
关闭程序,在idea启动,访问localhost:8888/helloworld/list。均可成功访问。
此步骤是为了在idea环境和命令行环境下均可正常运行

代码: https://gitee.com/eblly/jfinalCase

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容