原文: https://howtodoinjava.com/maven/tomcat-maven-plugin-example/

在本 maven 教程中,学习将 tomcat 插件添加并配置到pom.xml并使用它部署 Web 应用,而无需在机器上安装任何 tomcat。

当您想在由于某些原因无法安装实际 tomcat 的开发人员的机器上测试应用时,此功能非常有用。

插件的最新版本是“2.2”。 它具有 Apache Tomcat7 支持。

如何添加 tomcat Maven 插件

编辑项目的pom.xml文件和build标签内的插件项目。

  1. <build>
  2. <sourceDirectory>src/main/java</sourceDirectory>
  3. <resources>
  4. <resource>
  5. <directory>src/main/resources</directory>
  6. </resource>
  7. </resources>
  8. <plugins>
  9. <plugin>
  10. <artifactId>maven-compiler-plugin</artifactId>
  11. <version>3.5.1</version>
  12. <configuration>
  13. <source>1.8</source>
  14. <target>1.8</target>
  15. </configuration>
  16. </plugin>
  17. <!-- Tomcat plugin-->
  18. <plugin>
  19. <groupId>org.apache.tomcat.maven</groupId>
  20. <artifactId>tomcat7-maven-plugin</artifactId>
  21. <version>2.2</version>
  22. <configuration>
  23. <port>9000</port> //Configure port number
  24. <path>/spring5-webmvc-demo</path> //Configure application root URL
  25. </configuration>
  26. </plugin>
  27. </plugins>
  28. </build>

Tomcat Maven 插件配置

您可以在configuration标签内以各种方式添加 tomcat 插件。 一些有用的配置选项是:

  • address – 此 IP 地址将在所有端口上使用
  • contextFile – Tomcat 上下文 XML 文件的路径。
  • hostName – 配置主机名
  • httpsPort – 用于运行 Tomcat 服务器的 https 端口。
  • keystoreFile – 覆盖 HTTPS 连接器的默认密钥库文件(如果启用)
  • keystorePass – 覆盖 HTTPS 连接器的默认 keystorePass(如果启用)
  • mainClass – 用于启动独立 jar 的主类。
  • systemProperties – 要传递给 Tomcat 服务器的系统属性的列表。
  • port – 自定义端口号
  • path – 用于 Web 应用的 WebApp 上下文路径
  • warFile – 要部署的 WAR 文件的路径。

使用 tomcat 插件运行应用

要使用 tomcat maven 插件运行该应用,请将 maven 目标用作:

  1. mvn tomcat7:run

当您运行在 Maven 目标之上时,您会看到 tomcat 在控制台日志中使用默认端口8080启动。

  1. [INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ spring5-webmvc-demo >>>
  2. [INFO]
  3. [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring5-webmvc-demo ---
  4. [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
  5. [INFO] Copying 0 resource
  6. [INFO]
  7. [INFO] --- maven-compiler-plugin:3.5.1:compile (default-compile) @ spring5-webmvc-demo ---
  8. [INFO] Nothing to compile - all classes are up to date
  9. [INFO]
  10. [INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ spring5-webmvc-demo <<<
  11. [INFO]
  12. [INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ spring5-webmvc-demo ---
  13. [INFO] Running war on http://localhost:8080/spring5-webmvc-demo
  14. [INFO] Using existing Tomcat server configuration at D:\java9\workspace\spring5-webmvc-demo\target\tomcat
  15. [INFO] create webapp with contextPath: /spring5-webmvc-demo
  16. ---
  17. ---
  18. INFO: Starting ProtocolHandler ["http-bio-8080"]

将我的问题放在评论部分。

学习愉快!

参考: Tomcat Maven 插件文档