【问题标题】:Spring boot WAR deployed to Tomcat and missing context for static resourcesSpring boot WAR 部署到 Tomcat 并且缺少静态资源的上下文
【发布时间】:2017-03-05 08:34:20
【问题描述】:

在将 Spring Boot 应用程序作为 WAR 文件部署到独立的 Tomcat 7 服务器时遇到问题。它可以正常构建和部署,但是当 index.html 页面尝试加载其他静态资源时,它们会丢失 url 中的上下文,因此无法加载 (404)。

例如http://localhost:8080/app/images/springboot.png

应该是:http://localhost:8080/spring-boot-war-context-issue/app/images/springboot.png

Image showing issue

使用嵌入式Tomcat时效果很好

类似问题:

似乎与以下问题类似: Spring-Boot war external Tomcat context path

但是,该问题中的建议似乎并未解决我的问题。我不确定 Tomcat xml 文件。

后续步骤:

我创建了一个简单的示例应用程序并按照 Spring Boot 文档中的步骤进行操作。

可以在此 github 存储库中查看示例代码以及重现问题的步骤:https://github.com/jgraham0325/spring-boot-war-context-issue

到目前为止我尝试过的事情:

  • 在 application.properties 中设置 contextPath,但这仅适用于嵌入式 tomcat
  • 尝试使用全新安装的 Tomcat 7
  • 尝试在 tomcat 中创建配置文件以强制上下文: apache-tomcat-7.0.72\conf\Catalina\localhost\spring-boot-war-context-issue.xml

spring-boot-war-context-issue.xml的内容:

    <Context 
    docBase="spring-boot-war-context-issue" 
    path="spring-boot-war-context-issue" 
    reloadable="true" 
    />

任何建议将不胜感激!

谢谢

2016 年 10 月 23 日更新:

Alex 关于在开头使用不带斜线的相对 URL 的回答是完美的解决方案!

【问题讨论】:

  • websphere 8.5 服务器仍然存在这个问题

标签: java spring tomcat spring-boot


【解决方案1】:

如果使用Thymeleaf,另一种方法是使用Context-Relative URLs,如下所示:

<link rel="icon" type="image" th:href="@{/img/favicon.ico}"/>

更多信息请参考:Thymeleaf Documentation

【讨论】:

    【解决方案2】:

    不就是你在index.html中定义你的url的方式造成的吗(url不包括context root):

    <img src="/app/images/springboot.png" />
    

    使用相对 uri

    您应该能够使用相对 uri(没有前导正斜杠):

    <img src="app/images/springboot.png" />
    

    获取上下文根

    使用 JSP/JSTL:

    <img src="${pageContext.request.contextPath}/app/images/springboot.png" />
    

    或使用 Javascript:

    function getContextPath() {
       return window.location.pathname.substring(0,  window.location.pathname.indexOf("/",2));
    }
    ...
    var img = new Image();
    img.src = getContextPath() + "/app/images/springboot.png";
    document.getElementById('div').appendChild(img);
    

    【讨论】:

    • Alex,感谢您的详细回复,它解释了很多。我尝试将页面从 html 转换为 jsp 页面,并使用上述方法在本地运行良好,但在 tomcat 服务器上抛出错误 - 很可能只是一些配置问题。话虽如此,我们正在计划一个 Angular 应用程序,所以不要认为 JSP 是一种选择。考虑到每个链接需要多少额外的代码行,不确定纯 javascript 选项是否可行。也许最好将应用程序放在 Tomcat 的根目录中,或者这是不好的做法?
    • 你也可以使用相对 uri:。我将其添加到答案中。设置相对于您的 html 页面的路径。
    • 就是这样!非常感谢您的帮助 - 您是传奇人物。
    猜你喜欢
    • 2015-03-10
    • 2018-12-05
    • 2021-01-16
    • 2015-09-03
    • 2017-01-04
    • 2016-08-11
    • 2020-06-17
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多