Tomcat 不提供来自 maven-war-plugin 的文件

Tomcat not serving files from maven-war-plugin

我正在尝试让我的 Tomcat 服务器提供一个文件。我做了一个非常简单的例子来告诉你哪里出了问题,即使很简单,它也不起作用。

我的项目是这样制作的:

test
|->assets
|   |->testB.txt
|->src
|  |->main
|  |  |->webapp
|  |  |  |->WEB-INF
|  |  |  |  |->web.xml
|  |  |  |->testA.txt
|-> pom.xml

pom.xml

<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>assets/</directory>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat6-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
</web-app>

如果我执行 mvn package tomcat6:run,我可以访问 testA.txt 但我无法访问 testB.txt,即使当我查看 ".war”生成,我看到了:

|->testA.txt
|->testB.txt
|->META-INF
|->WEB-INF
|  |->web.xml
|  |->classes

我不明白为什么我可以访问一个但看不到另一个(404 错误)...

tomcat6:run 没有 运行 打包的 war,请尝试使用 mvn tomcat6:run-war

您无法访问 testB.txt,因为当 运行 tomcat6:run 时,Tomcat Maven 插件将默认查看 webapp 文件夹,而不是生成的 war 文件(通过 package 阶段)或在 target 文件夹中生成的解压 war。

这是有意为之,以便您可以即时创建新资源或更改其内容,并且更改将在 运行 实例(热部署)上可用。

您可以通过以下方式验证:

  • 在war文件中添加一个额外的testC.txt,它将被运行实例忽略
  • 在构建解压的war中添加一个额外的testC.txt,它将被忽略
  • 在 webapp 文件夹中添加一个额外的 testC.txt,它将可用!

来自其official documentation

The default location is ${basedir}/src/main/webapp

您可以通过 warSourceDirectory 元素对其进行配置。在您的情况下,您想将其指向 target 文件夹的内置解压 war。所以你可以改变你的配置如下:

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat6-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <path>/</path>
        <warSourceDirectory>${project.build.directory}/${project.build.finalName}</warSourceDirectory>
    </configuration>
</plugin>

注意:它现在指向通过 package 阶段构建的 Maven。它会起作用。