jfinal 內(nèi)嵌tomcat,打包可運行jar

[TOC]
當(dāng)需要快速開發(fā)并部署web項目時,傳統(tǒng)的方式需要在服務(wù)器上部署tomcat并配置端口等等配置,比較麻煩及低效率。而直接部署可運行jar的方式提供web服務(wù)效率會有比較大的提升。

項目結(jié)構(gòu)

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,現(xiàn)在為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>


    <!-- 分環(huán)境打包配置文件 -->
    <profiles>
        <!-- 本地環(huán)境 -->
        <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>

        <!-- 開發(fā)環(huán)境 -->
        <profile>
            <id>dev</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/dev</directory>
                    </resource>
                </resources>
            </build>

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

        <!--測試環(huán)境-->
        <profile>
            <id>tests</id>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources/tests</directory>
                    </resource>
                </resources>
            </build>
            <properties>
                <env.profile>tests</env.profile>
            </properties>
        </profile>

        <!--線上環(huán)境-->
        <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 包中的配置文件優(yōu)先級高于 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 等壓縮文件在被打包進(jìn)入 zip、tar.gz 時是否壓縮,設(shè)置為 false 可加快打包速度 -->
                            <recompressZippedFiles>true</recompressZippedFiles>
                            <!-- 打包生成的文件是否要追加 release.xml 中定義的 id 值 -->
                            <appendAssemblyId>true</appendAssemblyId>
                            <!-- 指向打包描述文件 package.xml -->
                            <descriptors>
                                <descriptor>package.xml</descriptor>
                            </descriptors>
                            <!-- 打包結(jié)果輸出的基礎(chǔ)目錄 -->
                            <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>

    <!--
        設(shè)置打包格式,可同時設(shè)置多種格式,常用格式有:dir、zip、tar、tar.gz
        dir 格式便于在本地測試打包結(jié)果
        zip 格式便于 windows 系統(tǒng)下解壓運行
        tar、tar.gz 格式便于 linux 系統(tǒng)下解壓運行
    -->
    <formats>
        <format>dir</format>
        <!--<format>zip</format>-->
        <format>tar.gz</format>
    </formats>

    <!-- 打 zip 設(shè)置為 true 時,會在 zip 包中生成一個根目錄,打 dir 時設(shè)置為 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 下的權(quán)限設(shè)為 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進(jìn)行打包。
打包后target結(jié)構(gòu)如下

image.png

進(jìn)入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
關(guān)閉程序,在idea啟動,訪問localhost:8888/helloworld/list。均可成功訪問。
此步驟是為了在idea環(huán)境和命令行環(huán)境下均可正常運行

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容