Maven web application embedded tomcat study notes

First create a maven web project


No


Two add embedded tomcat configuration in maven


<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>

 

Three Web project embeds Tomcat to realize jar operation

 

3.1 Add tomcat dependency

<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 Configuration file

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 Add loading class configuration 

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;
   /**
    *    
    * Initial loading configuration
    * @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("No configuration environment, use local configuration local");                 env = "local" ;             }             log.info("The current environment is: "+ 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 Embedded start 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("Failed to load configuration file.");                 System.exit(0);             }             // 1. Create an embedded Tomcat             Tomcat tomcat = new Tomcat();             // 2. Set the Tomcat port default to 8080             final Integer webPort = Integer.parseInt(EnvConfig.port);             tomcat.setPort(Integer.valueOf(webPort));             / / 3. Set the working directory, tomcat needs to use this directory to write something             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("The server has finished loading the configuration and is starting...");
            tomcat.start();
            log.info("Server started successfully");
            tomcat.getServer().await();
        } catch (Exception exception) {             log.error("Server failed to start", exception);         }     } }



3.5 Modify the packaging type

3.5.1 As a jar package

<packaging>jar</packaging>

3.5.2 Make a war package

<packaging>war</packaging>

 

3.6 Compile 

mvn clean package -Dmaven.test.skip=true

3.6 Operation

java -jar Denv = rc news-web.jar 

 

Introduction to four maven package run commands

4.1 The difference between maven package, install and deploy 

The mvn clean package executes seven stages of clean, resources, compile, testResources, testCompile, test, jar (packaging) in sequence.
mvn clean install executes 8 stages of clean, resources, compile, testResources, testCompile, test, jar (packaging), install in sequence.
mvn clean deploy executes nine stages of clean, resources, compile, testResources, testCompile, test, jar (package), install, and deploy in sequence.
From the above analysis, the main differences are as follows,

The package command completed the project compilation, unit testing, and packaging functions, but did not deploy the executable jar package (war package or other form of package) to the local maven warehouse and the remote maven private server warehouse. The
install command completed the project compilation, Unit testing and packaging functions. At the same time, the executable jar package (war package or other form of package) is deployed to the local maven warehouse, but it is not deployed to the remote maven private server warehouse. The
deploy command completes the project compilation, unit testing, Packaging function, and deploy the finished executable jar package (war package or other form of package) to the local maven warehouse and remote maven private server warehouse at the same time

 

4.2 tomcat maven plugin 

tomcat7:run和 tomcat7:run-war

Five maven setting configuration

5.1 Top-level elements 

  <localRepository/> This value represents the path of the local repository of the build system, its default value: ~/.m2/repository
  <interactiveMode/> indicates whether maven needs to interact with the user to get the input default true
  <usePluginRegistry/> Does maven need to use the plugin-registry.xml file to manage the plugin version, the default is false
  <offline/> indicates whether maven needs to run in offline mode. This configuration is very useful when the build server cannot connect to the remote warehouse due to network settings or security factors. The default is false
  <pluginGroups/> When the organization id (groupId) of the plug-in is not explicitly provided, it is used to search the list of plug-in organization Id (groupId). This element contains a list of pluginGroup elements, and each child element contains an organization Id (groupId). When we use a plugin and don't provide the organization ID (groupId) for it on the command line, Maven will use this list. By default, the list contains   <servers/>. Generally, the download and deployment of the warehouse are repositories and distributionManagement in the pom.xml fileorg.apache.maven.pluginsorg.codehaus.mojo
Defined in the element. Generally, however, a similar username, password ( some warehouse access is required safety certification ) and other information should not be configured in the pom.xml file, this information can be configured settings.xmlin
  <mirrors/>
 The list of download mirrors configured for the warehouse list. <mirrors>
    <!-- The download image of the given warehouse. -->
    <mirror>
      <!-- The unique identifier of the image. id is used to distinguish different mirror elements. -->
      <id>planetmirror.com</id>
      <!-- Mirror name-->
      <name>PlanetMirror Australia</name>
      <!-- The URL of the mirror. The build system will give priority to using this URL instead of using the default server URL. -->
      <url>http://downloads.planetmirror.com/pub/maven2</url>
      <!-- The id of the server being mirrored. For example, if we want to set up a mirror of the Maven central repository (http://repo.maven.apache.org/maven2/), we need to set this element to central. This must be exactly the same as the id central of the central warehouse. -->
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>

Activation

Role: profileConditional logic for automatic triggering .
As pom.xmlin profile, profileits function is that it can automatically use certain values ​​in certain environments; these environments activationare specified by elements.
activationElements are not profilethe only way to activate . settings.xmlFile activeProfileelement may contain profilea id. profileIt can also be activated explicitly by using the -P flag and a comma-separated list on the command line (for example, -P test).

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

5.2 Define activation multiple profiles and download sequence 

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

Six summary 

  Old, the single project is very large, so it has encountered many problems, and write it out as a record.

references

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

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

 

Guess you like

Origin blog.csdn.net/u013380694/article/details/107573107