gpt4 book ai didi

java - 部署到 Tomcat 的 Spring boot WAR 和缺少静态资源的上下文

转载 作者:行者123 更新时间:2023-11-30 10:37:12 24 4
gpt4 key购买 nike

我在将 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 的回答是完美的解决方案!

最佳答案

这不就是你在 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);

关于java - 部署到 Tomcat 的 Spring boot WAR 和缺少静态资源的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40203618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com