maven web应用嵌入式tomcat学习笔记

一 首先创建 maven web 工程


暂无


二 在maven 中添加嵌入式tomcat配置


<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <port>8080</port>
                <path>/</path>
            </configuration>
        </plugin>

<!-- 配置启动类 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>    <mainClass>com.twsm.embededtomcat.NewsWebMain</mainClass>
                        </manifest>
                    </archive>
                </configuration>

<!-- 打包加入依赖的包 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            </plugin>
    </plugins>
</build>

 <!-- 资源输出路径配置 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <!-- 是否替换资源中的属性 -->
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>${basedir}/target/webapp</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

三 Web工程内嵌Tomcat实现jar运行

3.1 加入tomcat依赖

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
    <version>8.5.51</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-el</artifactId>
    <version>8.5.51</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <version>8.5.51</version>
</dependency>

3.2 配置文件

application-local.properties
```
# Tomcat settings
tomcat.port=28080
tomcat.basedir=E:/fhcb10/news-web/tomcat/basedir


application-rc.properties
```
#Tomcat settings
tomcat.port=28080
tomcat.basedir=/data/fhcb10/news-web/tomcat/


3.3 添加加载类配置 

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**  
 * 环境配置加载类
 * @author  
 * @date 2018/6/5 11:38  
 */
public class EnvConfig {
    private final static Logger log = LoggerFactory.getLogger(EnvConfig.class);

    public static String port = null;

    public static String basedir = null;
    public static String filepath = null;
   /**
    *    
    * 初始化加载配置
    * @author
    * @date 2018/6/5 11:25  
    * @param []  
    * @return boolean  
    */  
    public static boolean init() {
        Configuration config;
        try {
            String env = System.getProperty("env");
            if (env == null) {
                log.info("没有配置环境,使用本地配置local");
                env = "local";
            }
            log.info("当前的环境是: " + env);
            String fileName = "application" + "-" + env + ".properties";
            config = new PropertiesConfiguration(fileName);
            port = config.getString("tomcat.port");
            if(port == null || port.isEmpty()) {
                port = "8080";
            }
            basedir = config.getString("tomcat.basedir");
            filepath = config.getString("filepath");
            log.info("==========================================");
            log.info("                    CONFIG                ");
            log.info("==========================================");
            log.info("port: " + port);
            log.info("docbase : " + basedir);
            log.info("filepath : " + filepath);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }
}

3.4 内嵌启动tomcat

package com.twsm.embededtomcat;

import com.twsm.embededtomcat.config.EnvConfig;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/**  
 *  内嵌Tomcat配置启动主类
 * @author huangyan 
 * @date 2018/6/5 11:38  
 */
public class NewsWebMain {
    private static Logger log = LoggerFactory.getLogger(NewsWebMain.class);
    /**  
     *    
     *  Tomcat 启动主类方法
     * @author huangyan 
     * @date 2018/6/5 11:39
     * @param [args]  
     * @return void  
     */  
    public static void main(String[] args) throws Exception {
        try {
            if (!EnvConfig.init()) {
                log.info("加載配置文件失敗。");
                System.exit(0);
            }
            // 1.创建一个内嵌的Tomcat
            Tomcat tomcat = new Tomcat();
            // 2.设置Tomcat端口默认为8080
            final Integer webPort = Integer.parseInt(EnvConfig.port);
            tomcat.setPort(Integer.valueOf(webPort));
            // 3.设置工作目录,tomcat需要使用这个目录进行写一些东西
            final String baseDir = EnvConfig.basedir;
            tomcat.setBaseDir(baseDir);
            tomcat.getHost().setAutoDeploy(false);
            // 4. 设置webapp资源路径
            String webappDirLocation = "webapp/";
            StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
            log.info("configuring app with basedir: " + new File("" + webappDirLocation).getAbsolutePath());
            log.info("project dir:"+new File("").getAbsolutePath());
            // 5. 设置上下文路每径
            String contextPath = "";
            ctx.setPath(contextPath);
            ctx.addLifecycleListener(new Tomcat.FixContextListener());
            ctx.setName("news-web");
            System.out.println("child Name:" + ctx.getName());
            tomcat.getHost().addChild(ctx);
           /* File additionWebInfClasses = new File("");
            WebResourceRoot resources = new StandardRoot(ctx);
            resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
                    additionWebInfClasses.getAbsolutePath() + "/classes", "/"));
            ctx.setResources(resources);
            */
            log.info("服务器加载完配置,正在启动中……");
            tomcat.start();
            log.info("服务器启动成功");
            tomcat.getServer().await();
        } catch (Exception exception) {
            log.error("服务器启动失敗", exception);
        }
    }
}

3.5 修改打包类型

3.5.1 打成jar包

<packaging>jar</packaging>

3.5.2 打成war包

<packaging>war</packaging>

3.6 编译 

mvn clean package -Dmaven.test.skip=true

3.6 运行

java -jar Denv=rc news-web.jar 

四 maven打包运行命令介绍

4.1 maven package,install ,deploy 区别 

mvn clean package依次执行了clean、resources、compile、testResources、testCompile、test、jar(打包)等7个阶段。
mvn clean install依次执行了clean、resources、compile、testResources、testCompile、test、jar(打包)、install等8个阶段。
mvn clean deploy依次执行了clean、resources、compile、testResources、testCompile、test、jar(打包)、install、deploy等9个阶段。
由上面的分析可知主要区别如下,

package命令完成了项目编译、单元测试、打包功能,但没有把打好的可执行jar包(war包或其它形式的包)布署到本地maven仓库和远程maven私服仓库
install命令完成了项目编译、单元测试、打包功能,同时把打好的可执行jar包(war包或其它形式的包)布署到本地maven仓库,但没有布署到远程maven私服仓库
deploy命令完成了项目编译、单元测试、打包功能,同时把打好的可执行jar包(war包或其它形式的包)布署到本地maven仓库和远程maven私服仓库

4.2 tomcat maven plugin 

tomcat7:run和 tomcat7:run-war

五 maven setting配置

5.1  顶级元素 

  <localRepository/> 该值表示构建系统本地仓库的路径 ,其默认值:~/.m2/repository
  <interactiveMode/> 示maven是否需要和用户交互以获得输入 默认true
  <usePluginRegistry/> maven是否需要使用plugin-registry.xml文件来管理插件版本,默认 false
  <offline/> 表示maven是否需要在离线模式下运行由于网络设置原因或者安全因素,构建服务器不能连接远程仓库的时候,该配置就十分有用 ,默认false
  <pluginGroups/> 插件的组织id(groupId)没有显式提供时,供搜寻插件组织Id(groupId)的列表。该元素包含一个pluginGroup元素列表,每个子元素包含了一个组织Id(groupId)。当我们使用某个插件,并且没有在命令行为其提供组织Id(groupId)的时候,Maven就会使用该列表。默认情况下该列表包含了org.apache.maven.pluginsorg.codehaus.mojo  <servers/> 一般,仓库的下载和部署是在pom.xml文件中的repositories和distributionManagement
元素中定义的。然而,一般类似用户名、密码(有些仓库访问是需要安全认证的)等信息不应该在pom.xml文件中配置,这些信息可以配置在settings.xml中
  <mirrors/>
 为仓库列表配置的下载镜像列表。 <mirrors>
    <!-- 给定仓库的下载镜像。 -->
    <mirror>
      <!-- 该镜像的唯一标识符。id用来区分不同的mirror元素。 -->
      <id>planetmirror.com</id>
      <!-- 镜像名称 -->
      <name>PlanetMirror Australia</name>
      <!-- 该镜像的URL。构建系统会优先考虑使用该URL,而非使用默认的服务器URL。 -->
      <url>http://downloads.planetmirror.com/pub/maven2</url>
      <!-- 被镜像的服务器的id。例如,如果我们要设置了一个Maven中央仓库(http://repo.maven.apache.org/maven2/)的镜像,就需要将该元素设置成central。这必须和中央仓库的id central完全一致。 -->
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>

Activation

作用:自动触发profile的条件逻辑。
pom.xml中的profile一样,profile的作用在于它能够在某些特定的环境中自动使用某些特定的值;这些环境通过activation元素指定。
activation元素并不是激活profile的唯一方式。settings.xml文件中的activeProfile元素可以包含profileidprofile也可以通过在命令行,使用-P标记和逗号分隔的列表来显式的激活(如,-P test)。

  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

5.2 定义激活多个profile并且下载顺序 

<activeProfiles>
            <!--make the profile active all the time -->
            <activeProfile>central-rep</activeProfile>
            <activeProfile>aliyun</activeProfile>
            <activeProfile>htsd-nexus</activeProfile>
            <activeProfile>htsd-nexus2</activeProfile>
    </activeProfiles>

六总结 

  老的,单体工程非常庞大所以遇到了很多问题,写出来作为记录。

参考文献

http://tomcat.apache.org/maven-plugin-2.0/tomcat7-maven-plugin/plugin-info.html

https://www.cnblogs.com/dalianpai/p/11850539.html

猜你喜欢

转载自blog.csdn.net/u013380694/article/details/107573107