美文网首页
jfinal 内嵌tomcat,打包可运行jar

jfinal 内嵌tomcat,打包可运行jar

作者: eblly | 来源:发表于2019-04-02 11:29 被阅读0次

    [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

    相关文章

      网友评论

          本文标题:jfinal 内嵌tomcat,打包可运行jar

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