为什么servletContext.getResourceAsStream获取可执行jar之外的文件?

时间:2018-05-09 13:03:09

标签: spring-boot servlets maven-3 tomcat8 embedded-tomcat-8

我正在从Spring Boot应用程序的war-packaging切换到使用可执行jar。

我的资源位于src/main/webapp下,根据Spring Boot docs(如果我理解正确的话),甚至不应该包含在最终的可执行jar中:

Do not use the src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar.

事实证明,在目标罐中我根本找不到这些资源。不幸的是,executable jar structure description似乎没有说明资源的位置。

然而,令我惊讶的是,在应用程序中调用servletContext.getResourceAsStream("/myresource.js")能够正确找到资源。资源似乎是从我的src/main/webapp目录提供的(即使以独立方式运行jar,例如通过java -jar myjar.jar

另外:

  • 调用servletContext.getResourcePaths列出了我的src/main/webapp目录
  • 的内容
  • 调用servletContext.getRealPath("/")会将文件系统上的确切路径返回给我的源文件,例如c:\path\to\my\project\src\main\webapp

为什么会这样?我希望我的jar里面只有应用程序可以使用的内容。嵌入式tomcat是否出于某种原因将我的源文件放在上下文根中?任何指向相关文档的链接都将受到赞赏。

P.S。在我的pom.xml中,您将看到标准内容:

<packaging>jar</packaging>
...
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
</parent>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.0.1.RELEASE</version>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
...
<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
...

0 个答案:

没有答案