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

一 首先创建 maven web 工程


暂无


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



   
       
            maven-compiler-plugin
            2.3.2
           
                1.8
                1.8
           

       

       
            org.apache.tomcat.maven
            tomcat7-maven-plugin
            2.2
           
                8080
                /
           

       


            
                org.apache.maven.plugins
                maven-jar-plugin
                3.0.2
                
                    
                        
                            true
                            lib/    com.twsm.embededtomcat.NewsWebMain
                        

                    

                


            
                org.apache.maven.plugins
                maven-dependency-plugin
                2.10
                
                    
                        copy-dependencies
                        package
                        
                            copy-dependencies
                        

                        
                            ${project.build.directory}/lib
                        

                    

                

            

            
   

 
        
            
                src/main/java
                
                    **/*.properties
                

                
                false
            

            
                src/main/resources
                
                    **/*.*
                

                false
            

            
                src/main/webapp
                ${basedir}/target/webapp
                
                    **/*.*
                

                false
            

        

    

 

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

 

3.1 加入tomcat依赖


    org.apache.tomcat.embed
    tomcat-embed-core
    8.5.51


    org.apache.tomcat.embed
    tomcat-embed-el
    8.5.51


    org.apache.tomcat.embed
    tomcat-embed-jasper
    8.5.51

3.2 配置文件

maven web应用嵌入式tomcat学习笔记_第1张图片

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包

jar

3.5.2 打成war包

war

 

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 web应用嵌入式tomcat学习笔记_第2张图片

五 maven setting配置

5.1  顶级元素 

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

Activation

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

  
  
  

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


            
            central-rep
            aliyun
            htsd-nexus
            htsd-nexus2
    

六总结 

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

参考文献

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

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

 

你可能感兴趣的:(互联网)